Add width and height attr to all images - javascript

I need width and height attributes added to all images on a page via javascript/jquery. This is due to a tool our systems use. I thought a simple each loop, adding height/width attr would suffice. Unfortunately this doesn't seem to work
DEMO https://jsfiddle.net/z86xnqd7/
$('body').find('img').each(function (index) {
var theWidth = index.width();
var theHeight = index.height();
index.attr({
"width": theWidth,
"height": theHeight
});
});
When you inspect element you will notice no width/height attr has been added

jsFiddle : https://jsfiddle.net/CanvasCode/z86xnqd7/6/
You need to do your each on the load event, you need to make sure your image has loaded before you check its height and width. Also you want to use $(this) instead of index.
$(function () {
$('img').load(function () {
var theWidth = $(this).width();
var theHeight = $(this).height();
$(this).attr({
"width": theWidth,
"height": theHeight
});
});
});

It's because index is real iteration index (e.g. 1, 2...). Use $(this) or add second parameter to function header function (index, element) {}:
$.each($('img'), function () {
$(this).attr({
width: $(this).width(),
height: $(this).height()
});
});

Problem here is that you try to get the width and height from the index which is just a number and no jQuery object. Try this - it will do the job:
$('body').find('img').each(function(i, elem) {
var $this = $(this);
var theWidth = $this.width();
var theHeight = $this.height();
$this.attr({"width": theWidth, "height": theHeight});
});
See js fiddle: https://jsfiddle.net/g4nn2pk0/2/

Related

Add pixels to existing CSS element with Javascript

here is my trouble.
I'm using a plugin for a lightbox. For some reason, one of the divs is 28px too short. I've looked all over for a solution for this, but nobody seems to be having the same problem.
The solution I've come up with is to find that element (which I have) and create a javascript snippet that will add "28" to the existing number. The height and width is being calculated directly on the div, not in an element in a stylesheet.
Example:
<div id="colorbox" class="" style="padding-bottom: 57px; padding-right: 28px; position: absolute; width: 892px; height: 602px; top: 2234px; left: 500px;">
I want the Javascript code to add 28 pixels to the width and 55px to the height.
How would I go about doing this?
I would like to say that I'm not looking for just an answer; if you could explain it to me, that would be great. Thanks so much, guys!
Edit: this is how I called the JQuery
Also, this is where you can see the page with the gallery: http://olsencustomhomes.com.previewdns.com/designs/verona-2/#gallery
EDIT FOR KRIS:
Is this the right code? It's in my header
<script>
$(document).ready(function() {
function changeSize(){
var colorbox = $("#colorbox");
var initWidth = $("#colorbox").outerWidth(); // get colorbox width
var initHeight = $("#colorbox").outerHeight(); // get colorbox height
var newWidth = 28; // set your desired width
var newHeight = 55; // set your desired height
var height = initHeight + newHeight; // add heights together
var width = initWidth + newWidth; // add widths together
colorbox.css({"height" : height, "width": width});
}
$(document).ajaxStop(function() {
changeSize();
});
});
</script>
Pretty straightforward application of jQuery, but I commented it up for you anyway:
//select the box element using jQuery
var box = $('#colorbox');
//get the current width and height
var curWidth = box.width();
var curHeight = box.height();
//set the width and height with modified values
box.width(curWidth + 28);
box.height(curHeight + 55);
fiddle: http://jsfiddle.net/579s2/
If you want to add height and width dynamically. Something like this should work:
function changeSize(){
var colorbox = $("#colorbox");
var initWidth = $("#colorbox").outerWidth(); // get colorbox width
var initHeight = $("#colorbox").outerHeight(); // get colorbox height
var newWidth = 28; // set your desired width
var newHeight = 55; // set your desired height
var height = initHeight + newHeight; // add heights together
var width = initWidth + newWidth; // add widths together
colorbox.css({"height" : height, "width": width});
}changeSize();
Also if you want to insure your code is happens after the colorbox opens you could use .ajaxStop(); Also note, outerWidht() and outerHeight() will get colorbox width plus the padding and borders.
To fire function after ajax events are finished:
$(document).ajaxStop(function() {
changeSize();
});
Update:
Okay, it looks the function fires initially. You can see width is null because the colorbox has not opened. What you want to do is fire the function after the colorbox opens. That is where ajaxStop() would come into play. But it might actually be better to use the colorbox callback function:
But not after the colorbox opens. So try doing the ajaxStop() approach. Also note, if you do this you will need to remove changeSize(); after function changeSize() For example:
$(document).ready(function() {
function changeSize(){
// function stuff
}
$(document).ajaxStop(function() {
changeSize();
});
});
Or, Colorbox OnComplete:
$(".selector").colorbox({
onComplete:function(){
changeSize();
}
});
Update 2:
I am not sure where you are calling colorbox exactly. But I see you have this: Found here
jQuery(function($){
$('#wpsimplegallery a').colorbox({
maxWidth: '85%',
maxHeight: '85%'
});
});
So try:
jQuery(function($){
$('#wpsimplegallery a').colorbox({
maxWidth: '85%',
maxHeight: '85%',
onComplete:function(){
changeSize();
}
});
});

Get DIV width and height in javascript

I'm trying to get the div width and height as the user changes it and submit that number to another page. I can't seem to figure out how to get the width and height though.
<script>
$(function() {
$( "#set div" ).draggable({
stack: "#set div",
preventCollision: true,
containment: $('#main_content'),
stop: function(event, ui) {
var mydiv = document.getElementById("set");
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
var width = mydiv.style.width; ----THIS DOESN'T WORK
var height = mydiv.style.height; ----THIS DOESN'T WORK
var window_width = window.innerWidth;
var window_height = window.innerHeight;
var need = ui.helper.data("need");
console.log(pos_x);
console.log(pos_y);
console.log(width);
console.log(window_width);
console.log(need);
//Do the ajax call to the server
$.ajax({
type: "POST",
url: "updatecoords.php",
data: { x: pos_x, y: pos_y, need_id: need, width: width, height: height, window_width: window_width, window_height: window_height}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
});
</script>
What's the proper way to do this?
It's quite wrong to use ele.style.width to get the element's width!!!!!!
In native JavaScript, you can get a element's CSS through two ways:
Standard Method
window.getComputedStyle(ele)
For example,
var ele = document.getElementById("content"), // Do not use #
eleStyle = window.getComputedStyle(ele);
/* Below is the width of ele */
var eleWidth = eleStyle.width;
IE(IE 8 And Before)
element.currentStyle
For example,
var ele = document.getElementById("content"), // Do not use #
eleStyle = ele.currentStyle;
/* Below is the width of ele */
var eleWidth = eleStyle.width;
Why Not Use ele.style?
ele.style is just get the attribule style of ele. If you use ele.style.width, you just get the width of ele.style, not the real width of ele.
If you have done something like:
ele.style.width = "55px"
You get "55px" when using ele.style.width. If you haven't, you will get undefined.
How To Do In jQuery?
Use $ele.width() (if you want the "exact" width, use $ele.outWidth()), jQuery has done everything for you.
In plain vanilla JavaScript use
var width = mydiv.offsetWidth;
var height = mydiv.offsetHeight;
This will give you numeric values, or
var width = mydiv.offsetWidth + 'px';
var height = mydiv.offsetHeight + 'px';
If you want them in "CSS" format.
Since you're already using jQuery, you can just do:
var width;
if (need == 1) {
width = $("#web").width();
} else {
width = $("#set").width();
}
Since you're using jQuery, you'll probably want to know about the following:
$('#id').outerWidth()
$('#id').outerWidth(true)
These will come in very handy. This allows you to find the total width of the div (padding, border, width and (optional argument) margin).
http://api.jquery.com/outerWidth/

get height of LI using jQuery so news ticker scrolls up the exact amount needed

I am using a script from
http://www.yourinspirationweb.com/en/jquery-how-to-create-a-news-ticker-with-just-a-few-javascript-lines/
which is a great newsticker, designed to scroll up just one article at a time, then append it again at the end in a continuous loop. But the limitation of this script is that the news items in each have to be the same height as eachother, which isn't always possible.
I have been trying to modify the script so that it will automatically get the outerheight of '#ticker li:first'. and scroll it so that marginTop equals the negative of that outerheight. rather than the default '-120px'. But i've realised it's written as CSS style, i don't know how to rewrite it. Help!
here's the original script:
$(function()
{
var ticker = function()
{
setTimeout(function(){
$('#ticker li:first').animate( {marginTop: '-120px'}, 800, function()
{
$(this).detach().appendTo('ul#ticker').removeAttr('style');
});
ticker();
}, 4000);
};
ticker();
});
This should do the trick. Just put the height into a variable, multiply by -1 (to make the negative number you need), and then drop it into the marginTop property:
$(function() {
var ticker = function() {
setTimeout(function() {
// get the height of the li element, multiply by -1 to be negative
var h = parseInt($("#ticker li:first").outerHeight()) * -1;
$('#ticker li:first').animate( {marginTop: h + 'px'}, 800, function() {
$(this).detach().appendTo('ul#ticker').removeAttr('style');
});
ticker();
}, 4000);
};
ticker();
});
To retrieve the outerHeight (including border, padding, and optionally margin) of an html element using jQuery, do $(element).outerHeight()
To retrieve the innerHeight of an html element using jQuery, do $(element).innerHeight()
$(function()
{
var ticker = function()
{
setTimeout(function(){
var oHeight = $('#ticker li:first').outerHeight();
$('#ticker li:first').animate( {marginTop: -oHeight}, 800, function()
{
$(this).detach().appendTo('ul#ticker').removeAttr('style');
});
ticker();
}, 4000);
};
ticker();
});
The default unit is pixels so you don't have to worry about appending px to the value.

Setting DIV width based on child image

I am trying to set DIV width based on the child image. This code below works if there is only one DIV. When there are more, it will only use the width of the first child image (first DIV).
$('.img_thumb').each(function(){
$('img').load(function(){
var img_width = $('.img_thumb img').width();
$('.img_thumb').css('width', img_width + 'px');
});
});
Any help would be appreciated. Thanks
In the .load() callback, use this to refer to the specific image of interest. Get rid of the .each().
$('img').load(function(){
var $this = $(this),
img_width = $this.width();
$this.closest('.img_thumb').css('width', img_width + 'px');
});
On line 3 you have a reference to the object $('.img_thumb img'):
var img_width = $('.img_thumb img').width()
Which is always going to point to the first element. You need to use $(this) when you're inside the .each in order to target the current element:
var img_width = $(this).width()
Try this:
$('.img_thumb').each(function(){
var _this = $(this);
$(this).find('img').load(function(){
_this.css('width', $(this).width() + 'px');
});
});

Accessible and dynamic animated information box

I have started with the example and added to the code to make it:
Dynamic in height
Accessible with JS turned off
Have I done this correct? Will this work on most browsers?
Working version visable here:
Original:
$('#example-links a').hover(function(){
var index = $("#example-links a").index(this);
$('#example-content').animate({"marginTop" : -index*220 + "px"}); // multiply by height+top/bottom padding/margin/border
});
My modified code, it just seems a little long compared to the above:
var maxHeight = 0, container_maxHeight = 0;
var example_content = $("#example-content");
var example_div = example_content.children("div");
example_div.each(function() {
if($(this).height() > maxHeight) {
maxHeight = $(this).height();
container_maxHeight = $(this).outerHeight(true);
}
});
example_div.height(maxHeight);
$("#example-content-container").css({
"overflow":"hidden",
"height": container_maxHeight+"px"
});
$('#example-links a').bind('click mouseover', function(e){
var index = $("#example-links a").removeClass("active").index(this);
$(this).addClass("active");
example_content.stop().animate({"marginTop" : -index*container_maxHeight + "px"});
e.preventDefault();
});
I bind both the click and mouseover because I want it to work via mouseover but then I also want it to work when browsing on a mobile phone that doesn't have a mouse to activate the hover.
Everything seems fine, the only thing I would add to make it more accessible if JS is off, are the section ids. You can check it here.
For each section, you add an id to the wrapping div, and then on your side links you link to that id.
I would clean up your code a little bit more:
(function($){
$(document).ready(function(){
var maxHeight = 0, container_maxHeight = 0,
example_content = $("#example-content"),
example_div = example_content.children("div");
example_div.each(function() {
var $section = $(this);
if($section.height() > maxHeight) {
maxHeight = $section.height();
container_maxHeight = $section.outerHeight(true);
}
});
example_div.height(maxHeight);
$("#example-content-container").height(container_maxHeight);
var $tabs = $('#example-links a');
$tabs.bind('click mouseover', function(e){
var index = $tabs.removeClass("active").index(this);
$(this).addClass("active");
example_content.stop().animate({"marginTop" : -index*container_maxHeight + "px"});
e.preventDefault();
});
});
})(jQuery);

Categories

Resources