Created
April 8, 2015 07:53
-
-
Save sdelamo/e852efb67a1bb2ed8bf1 to your computer and use it in GitHub Desktop.
Change width and height of images and iframe elements which have these attributes set directly. Useful in wordpress theme development for responsive design
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function () { | |
$(document).ready(function() { | |
var padding = 10; | |
$('img').each(function () { | |
changeElementWidthAndHeightToFitParentSize($(this),padding); | |
}); | |
$('iframe').each(function () { | |
changeElementWidthAndHeightToFitParentSize($(this),padding); | |
}); | |
}); | |
}); | |
function changeElementWidthAndHeightToFitParentSize(el,padding) { | |
var width = el.attr('width'); | |
if (typeof width != 'undefined') { | |
var parentWidth = getParentWithStyle(el,'block').width(); | |
if(width > parentWidth) { | |
var height = el.attr('height'); | |
var newWidth = parentWidth; | |
newWidth -= padding; | |
el.attr('width',newWidth); | |
if (typeof height != 'undefined') { | |
var ratio = height / width; | |
var newHeight = newWidth * ratio; | |
el.attr('height',newHeight); | |
} | |
} | |
} | |
} | |
function getParentWithStyle(el,elementStyle) { | |
var tagName = jQuery(el.parent()).prop("tagName"); | |
if(getElementDefaultDisplay(tagName) == elementStyle) { | |
return el.parent(); | |
} | |
return getParentWithStyle(el.parent(),elementStyle); | |
} | |
function getElementDefaultDisplay(tag) { | |
var cStyle, | |
t = document.createElement(tag), | |
gcs = "getComputedStyle" in window; | |
document.body.appendChild(t); | |
cStyle = (gcs ? window.getComputedStyle(t, "") : t.currentStyle).display; | |
document.body.removeChild(t); | |
return cStyle; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment