JQuery Load all images inside div before display - javascript

I want to load every image inside a div before actually displaying them. I have something similar to this:
<div>
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
</div>
At first I tried doing things like:
$('div img').load(function() {
$('div img').show();
});
Or this:
$('div').find('img').load(function() {
$('div img').show();
});
Unfortunately, this didn't work because once the browser loads even just a single image, it fires the event. Any ideas on how to load everything first ? Thanks!

You can keep track of how many images have loaded:
var $images = $('div img'),
preloaded = 0,
total = $images.length;
$images.load(function() {
if (++preloaded === total) {
// Done!
}
});

Unfortunately there is not easy way to do this in a cross browser compatible way. But luckily there are 2 plugins out there that can make it painless.
Check out waitforimages and imagesloaded
Then you can do:
$('div').waitForImages(function(){
$(this).find('img').show();
});

Try this
http://chipsandtv.com/articles/jquery-image-preload

First, The modern browser can execute concurrently 6 request => Don't load so many image at the load time. If you have many images, you can set the images at the back 'src=""' or non set "src" attributes, And set after the first images loaded
Second, You can check "image was loaded" by using
document.getElementById('#imageId').complete == !0
You can check with image with the largest size or the last image in DOM to make sure the others images were loaded.
Hope it 'll help you.

This worked for me:
$(document).ready(function () {
$('#div with images').hide();
});
$(window).load(function () {
$('#div with images').show();
});

Related

Jquery dynamically enter values

below is my code
<img src="1.gif"></i>
<img src="2.gif">
as shown in the above code when user clicks on smiley image it changes the value of text area #chat_textarea values are different for different smiley images,above code works fine... but what if i have more then 100 smileys? is there any way i can change the value of chat_textarea dynamically...? because to load images Iam just for loop which loads all images 1 to given number...
Updated:Hi all I know that we can use classname
$('.add_smile').on('click', function(){
// Prepend the ALT of the image to the textarea
$('#chat_textarea').val( $('#chat_textarea').val()+ this.alt );
});
But my question is different...i can not add alt / value to each image, it should be loaded automatically,something like fetching ;) from json file by passing id ....is there any ways to fix in that way....
Below some simpeler html.
If you want to load them dynamicly, just use your language of choice to loop through an array:
// Php
foreach($smileys as $img=>$code){ echo '<img src="'.$img.'" alt="'.$code.'" />';}
// Javascript
$.each(smileys, funcion(index,smile){
$('#smileWrap').append('<img src="'+smile.src+'" alt="'+smile.alt+'" />')
});
<img class="add_smile" src="/img1.jpg" alt=":)" />
<img class="add_smile" src="/img2.jpg" alt=":(" />
<img class="add_smile" src="/img3.jpg" alt=";)" />
$('.add_smile').on('click', function(){
// Prepend the ALT of the image to the textarea
$('#chat_textarea').val( $('#chat_textarea').val()+ this.alt );
});
jQuery doesnt care what you add the click to, the image is just fine. If you want a pointer as mouse, just css that.
Now you can use php to loop and place as many images as needed. Images are required to have an alt, that's fixed. And we can easily access it in javascript, not needing extra html (the anchor) to get that.
My jsFiddle, with auto space-add if not present
Remove unnecessary links, add a ClassName and a data-val attribute to each smiley and modify your HTML like this:
<img src="1.gif" class="smiles_btn" data-val=':#'>
<img src="2.gif" class="smiles_btn" data-val='8D'>
<img src="1.gif" class="smiles_btn" data-val=':#'>
<img src="2.gif" class="smiles_btn" data-val='8D'>
Then use this JQuery:
$('.smiles_btn').click(function(){
$('#chat_textarea').val($('#chat_textarea').val() + ' ' + $(this).data('val')).focus();
});
Check JSFiddle Demo

How to replace multiple images with Javascript and change back

I've been working on trying to get these buttons to change when clicked - which now works, but now I need them to toggle between the on and off states when the user clicks (so they can turn the buttons on and off). I'm sure this is an easy fix, but I'm new to Javascript and I don't have anyone to bounce ideas off of.
<html>
<head>
<script type="text/javascript">
function changeimage(img, new_src)
{
var cur_src = img.src.substring(img.src.lastIndexOf("/")+1);
if (cur_src == new_src)
{
img.src = img.old_src;
}
else
{
img.old_src = cur_src;
img.src = new_src;
}
}
</script>
</head>
<body>
<img onclick="changeimage(this, 'images/buttonA_on.png')" src="images/buttonA_off.png" />
<img onclick="changeimage(this, 'images/buttonB_on.png')" src="images/buttonB_off.png" />
<img onclick="changeimage(this, 'images/buttonC_on.png')" src="images/buttonC_off.png" />
<img onclick="changeimage(this, 'images/buttonD_on.png')" src="images/buttonD_off.png" />
<img onclick="changeimage(this, 'images/buttonE_on.png')" src="images/buttonE_off.png" />
<img onclick="changeimage(this, 'images/buttonF_on.png')" src="images/buttonF_off.png" />
</body>
</html>
Much thanks!
When I started using JavaScript I wasted a bunch of time trying to do things that other libraries could easily take care of for me. A few months after that I discovered jQuery which has drastically reduced the amount of time I spend on front-end projects. All you have to do is include the jQuery file in an html project and you're good to go.
In jQuery, you can toggle a class on and off with one line. it looks something like this:
$('.toggleimage').toggleClass('on');
In the above example, '.toggleimage' is just a class I gave to a div, toggleClass is the jQuery command, and 'on' is the name of the class I want to toggle. This probably seems like greek right now, but I recommend going through codeschool's jQuery tutorials to get caught up. If you're thinking of doing serious web development... it's a crucial tool. Here is the full code:
link to full code on my Gist
In order to make it work, make sure you have the right file structure. Create a folder, then create the html file there. In addition, create three subfolders (one for css, one for images, one for scripts). The css folder holds your style.css, the images folder holds mario.jpg, and the scripts folder contains your jQuery file. You can substitute in any image you want, just make sure the changes are applied to style.css.
function changeImg(img) {
if ( img.src.indexOf("_off") > 0 ) {
img.src = img.src.replace("_off","_on");
}
else {
img.src = img.src.replace("_on","_off");
}
}
it will work if you have 50x2 different images, named "imgName1_uw.jpg", "img1_moored.jpg", "img2_uw.jpg", "img2_moored.jpg", etc.
may be its helps you

javascript change Image by clicking thumbnail

I am a newbie in javascript and tried a lot of things for hours, but nothing worked.
I will change a big imgage by clicking on a thumbnail.
Untill now I got following script. Not much really... :-(
<script type="text/javascript">
function changeImage() {
document.getElementById("img").src="img/upload/test1.jpg";
}
</script>
<img id="img" name="change" src="img/upload/test.jpg">
<img src="img/thumbnail/test.jpg" alt="" id="imgClickAndChange" onclick="changeImage()">
<img src="img/thumbnail/test1.jpg" alt="" id="imgClickAndChange" onclick="changeImage()">
All big picture are under src"img/upload/xxx.jpg" and all thumbnails under src="img/thumbnail/xxx.jpg". When I click the thumbnail, it have to change the big picture and it have to give the parameter in the javascript. Like onclick="changeImage(xxx.jpg).
The problem is every page have other pictures. I get them from a database. So the name of the picture is like a variable. I hope you understand. It is hard for me to explain. :-(
Thanks for your help in advance.
Greets Yanick
Pass the image parameter to the function like,
function changeImage(image) {
document.getElementById("img").src=image;
}
<img src="img/thumbnail/test.jpg" alt="" id="img"
onclick="changeImage('img/upload/test1.jpg')" />
Keep ids unique. DOM elements "must" possess unique IDs for all practical reasons.
Though you could do an inline onclick, a better way to proceed with it is something as follows.
Assuming you have the images generated from some templating library either on the client or from the server, add data attributes with the image sources and a common class to all of these elements right there and add an event listener from your Javascript bound to elements matching the class and picking up the data attribute to replace the image source.

Grails: JS function to change src of img is not responding

I am trying to change the src of an img under a certain condition. I know the condition returns true appropriately, because I previously wrote in an alert(). For some reason, the function is not changing the src of the img and dynamically updating the page. Could this have anything to do with the fact that I am using the jquery library? I would think you can still use the stand js syntax. Here are my code snippets and the corresponding source code from google chrome.
.gsp:
<script type="text/javascript">
function onSuccess(data){
if(data.hasHearted){
document.getElementById("changer${user.id}").src = "${resource(dir: "images/images", file: "heart_red.png")}";
}
}
<figcaption id="secondcap" onClick="${remoteFunction(controller:'user', action:'heart', onSuccess: 'onSuccess(data)', params:[userID:user.id])}">
<img id="changer${user.id}" src="${resource(dir: "images/images", file: "heart.png")}" alt="heart">
</figcaption>
Chrome source (I've omitted some things for privacy):
<script type="text/javascript">
function onSuccess(data){
if(data.hasHearted){
$('#changer3').attr('src','/Personably/static/images/images/heart_red.png');
}
}
</script>
<div class="persons">
<figure class="user_image">
<img class="user_profile_pic" src="omitted for privacy..." onmouseover="jQuery.ajax({type:'POST',data:{'userID': '3'}, url:'/Personably/user/hasHearted',success:function(data,textStatus){onSuccess(data);},error:function(XMLHttpRequest,textStatus,errorThrown){}});"/>
<figcaption id="firstcap">
Omitted for privacy...
</figcaption>
<figcaption id="secondcap" onClick="jQuery.ajax({type:'POST',data:{'userID': '3'}, url:'/Personably/user/heart',success:function(data,textStatus){onSuccess(data);},error:function(XMLHttpRequest,textStatus,errorThrown){}});">
<img id="changer3" src="/Personably/static/images/images/heart.png" alt="heart">
</figcaption>
</figure>
</div>
Since you are using jquery, have you tried using the jquery id selector $(“#id”) and/or the jquery .attr function?
http://api.jquery.com/id-selector/
http://api.jquery.com/attr/#attr2
I'm not sure that changing the src attribute after the page is loaded will change what the user sees, even if it changes the code, because the document is already loaded.
Instead, you should probably put both images (heart.png and heart_red.png) on the page, and then hide/unhide them with styles depending on the output of your controller action. The jquery .toggle(Boolean) method can be very useful for stuff like this. http://api.jquery.com/toggle/
Inside your JavaScript function, you could just have something like:
$('#heart3').toggle(!data.hearted);
$('#heart_red3').toggle(data.hearted);
Then, when data.hearted is true, red heart will show, and plain heart will hide.

Javascript get image source and inject into another image source

I've been working on a Javascript photo gallery and I want it to be very user-friendly. This involves only having to use one image and one link per image. I have it so all the images appear in a scrolling div on the left and onClick it is suppose to change the image source on the right but I can't seem to get javascript to get the image source from the original image and change the second one with it. I've tried a few other ways but this is the way I like and if I could get it to work it would be perfect.
This is inside a table so it is align differently I'm just giving the code needed.
This code was given below but it seems as though he deleted his answer. I think you were much close than me!
Javascript:
<script type="Text/javscript">
function setImage(this) {
document.getElementById("ImageFrame").src = this.childNodes[0].src;
}
</script>
break
<div style="width:275;height:400;overflow-x:scroll;">
<img class="gallery" src="JCF/PICT0421.jpg" />
<img class="gallery" src="JCF/PICT0422.jpg" />
<img class="gallery" src="JCF/PICT0423.jpg" />
</div>
The image being changed.
<div>
<img id="ImageFrame" src="JCF/PICT0421.jpg" width="400" />
</div>
here is a working example. NOTE: a.getElementsByTagName('img')[0].src as different browsers would add nodes to tag before and after the child tag. It is safe to use getElementsByTagName('img')[0].src
<html>
<head>
<script type="text/javascript">
function setImg(a){
//alert(a.getElementsByTagName('img')[0].src);
document.getElementById('ImageFrame').src =
a.getElementsByTagName('img')[0].src
}
</script>
</head>
<body>
<img src="JCF/PICT0421.jpg">
<div>
<img id="ImageFrame" src="JCF/PICT0421.jpg" width="400" />
</div>
</body>
</html>
var pic1 = document.getElementById("image1");
var src = pic1.src; // here is the src for image1
var pic2 = document.getElementById("image2");
pic1.src = src; // here we set the src for image2
So this code will take the image src from image1 and put it in image2.
I believe something like this should work for you:
HTML:
<img class="gallery" id="image1" src="image1.jpg" />
Javascript:
function setImage(imgParent) {
document.getElementById("ImageFrame").src = imgParent.childNodes[0].src;
}​
Live DEMO
The Demo will work better when you actually load in images. However, if you inspect the broken images, you can see that it is loading in the new image correctly.
Edit:
Since Kaf mentioned that he has had issues with childNodes, you may want to try this out instead:
Javascript:
function setImage(imgParent) {
document.getElementById("ImageFrame").src = imgParent.getElementsByTagName('img')[0].src;
}​
assuming you can use Jquery
$('.imageClass').click(function(){
var srcToCopy = $(this).attr('src');
$(somewheretoputsrc).attr('src', srcToCopy);
})
this code should work
edit : fiddle edited with working image
http://jsfiddle.net/jbduzan/b7adx/1/
You should go with so called "Unobtrusive JavaScript", i.e. don't mix content with JavaScript and apply the desired behaviors after the window has been loaded.
Something like that:
function addDomListener(element, eventName, listener) {
if (element.addEventListener) // most browsers
element.addEventListener(eventName, listener, true);
else if (element.attachEvent) // IE
element.attachEvent('on' + eventName, listener);
}
window.onload = function() {
var elements = getElementsByClassName('thumb-link');
for (int i=0; i < elements.size(); i++) {
var el = elements[i];
addDomListener(el, "click", function () {
setImage(el);
});
}
}
getElementsByClassName still needs an implementation here and every a tag that had onlick previously needs the class 'thumb-link'. But I'm sure you'll figure that out.
Using a library like jQuery or Prototype.js would make it easier here...

Categories