Javascript, HTML, Demos, Tutorials

Dynamically set iframe properties with jQuery

Using jQuery it’s possible to pass properties to set the src, width and height of an iframe from a series of links. 

Give the links a class for jQuery to read and set data properties, you can call these anything but using the named properties makes sense so set data-src, data-width and data-height. 

<a class="item" data-src="" data-height="350" data-width="100%">Link</a>

Next the jquery (this snippet assumes you’ve already included jquery).

Looking for click events the class item is looked for then the data attributes are collected by using $(this).att(data-src) the data-src must match what’s set in the link, in the below snippet the width and height has a set value for cases where no width and height has been set.

Then the iframe inside #itemcontent is identified and the properties are applied.

$('a.item').on('click', function(e) {
  var src = $(this).attr('data-src');
  var height = $(this).attr('data-height') || 300;
  var width = $(this).attr('data-width') || 400;
  $("#itemcontent iframe").attr({'src':src,'height': height,'width': width});

Finally have the div with an iframe.

<div id='itemcontent'>


David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.