Paha
Paha

Reputation: 99

Applying Jquery to dynamically created images

I'm new to Javascript/Jquery and PHP and I'm experimenting with it. Basically, I've created a simple image gallery in which each picture is at an opacity of .4 until you mouse over it and it becomes 100% opacity. Now I've gone a step further and used PHP to scan a directory of images and add them to the list of pictures in the gallery. The current code looks like this:

$(document).ready(function(){

var i = 0;
var names;

function returndata(files){
    names = files;

    for(i=0; i < names.length ; i++){
        $('<li id="img_' + i + '"><img src="../Gallery_pictures/' + names[i] + '"/></li>').appendTo('#thumbnails ul');
    }       
}

 $.post('../php/read_directory.php',function(data){
    var files = $.parseJSON(data);
    returndata(files);
    });
});

The code works and adds the images to the list on the webpage, but how would I go about adding the Jquery fade to the newly created images? I've searched all over the place for an answer to this but maybe I'm just missing the answers. This and the image fade are in separate external Javascript files. Thanks in advance.

*EDIT:*Okay so I got it to work using your suggestions, but the problem now is that the script doesn't start until an image is initially moused over. All the pictures start full opacity until moused over then they all become .4 opacity. Any way to fix this? I'm also going to try if I can easily do this in css.

*DOUBLE EDIT:*So I can easily do this with css and it works like I want it to. Thanks for the replies everyone.

Upvotes: 4

Views: 362

Answers (3)

mas-designs
mas-designs

Reputation: 7536

Try to add class="hoverImg" to your img and then do the following:

$('.hoverImg').on('hover',function(){
       // here goes your hover code
});

So every image has the class .hoverImg also the new ones. And you bind the event hover on every single image that has the class .hoverImg. And why do you have to use .on() simply because this makes sure that the code is also executed if img's are added to your dom after it has been fully loaded.

Upvotes: 0

Adam Rackis
Adam Rackis

Reputation: 83356

Use on to set events on dynamically added content

$(document).on("mouseover", "#thumbnails img", function() {
    $(this).css("opacity", 1); 
});

$(document).on("mouseout", "#thumbnails img", function() {
    $(this).css("opacity", 0.4); 
});

If you're using jQuery pre 1.7, then you can use delegate. Note that delegate takes the selector first, then the event name.

$(document).delegate("#thumbnails img", "mouseover", function() {
    $(this).css("opacity", 1); 
});

$(document).delegate("#thumbnails img", "mouseout", function() {
    $(this).css("opacity", 0.4); 
});

Avoid using live since it's deprecated.

Upvotes: 1

Ajinkya
Ajinkya

Reputation: 22710

Use .live() or .on() to bind event to dynamically added elements.
.live() is deprecated in jQuery 1.7

Upvotes: 0

Related Questions