Applying jquery to dynamically generated images

I am new to Javascript / JQuery and PHP and I am experimenting with it. Basically, I created a simple image gallery in which each picture has an opacity of .4 until you click on it and it becomes 100% opaque. Now I took another step and used PHP to scan the catalog of images and add them to the list of images 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 web page, but how can I add a jQuery add to the newly created images? I have searched all over the place for an answer to this, but maybe I will just skip the answers. This and the image disappear in separate external Javascript files. Thanks in advance.

* EDIT: * Good, so I got it to work with your suggestions, but now the problem is that the script does not run until the image is first blurred. All images start with full opacity until they are hidden, and then they all become opaque. 4. Any way to fix this? I will also try if I can easily do this in css.

* DOUBLE EDIT: * Therefore, I can easily do this with css, and it works the way I want. Thanks for all the answers.

+4
source share
3 answers

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 are using jQuery pre 1.7, you can use delegate . Note that the delegate first accepts the selector and 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 as it is deprecated .

+1
source

Try adding class="hoverImg" to your img , and then follow these steps:

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

Thus, each image has a .hoverImg class and new ones. And you bind an event, hover over each image that has a .hoverImg class. And why you should use .on() simply because it guarantees that the code will also be executed if img is added to your dom after it is fully loaded.

0
source

Use .live() or .on() to associate an event with dynamically added elements.
.live() deprecated in jQuery 1.7

0
source

Source: https://habr.com/ru/post/1387694/


All Articles