I’m using a function to add images to a site. These go into a DIV, using .html()
After that’s done I need those same images to show an effect on hover, but nothing happens when I hover them.
If I type the same code I use in the .html() function, same class, etc, hover works.
After lots of attempts, I narrowed my problem to this sample.
Turns out the problem is how the container DIV exposes the code added through .html() … and my hover functions can’t find the dynamically added tags.
Here’s my sample code:
<html>
<head>
<title>Problems</title>
<script type ="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<p id="TXToldone">This line was already here</p>
<div id="DIVnewone"></div>
<script>
function createnewone(){
$txthtml="<p id=\"TXTnewone\">And this one got added dynamically</p>";
$("#DIVnewone").html($txthtml);
};
$(document).ready(function() {
createnewone();
});
$("*").on("click", function(){
alert( $(this).attr("id") );
});
</script>
</body>
</html>
Notes:
– This is just a raw example of my real problem. This is not what I’m
actually trying to accomplish, but solving this one would make me
solve the real one 😉
– The first two functions are from the actual code … after document
is ready I load the pics and recursively add the html required to
each DIV …
– Third function is just so you guys can see my problem … It should
be showing an alert with the ID of the element you click on (and it
does for the 1st paragraph) … but check what happens when you click
the second one … you don’t see the ID for that paragraph but the ID
for the container DIV instead!
– (yes, it also gives alerts for the other parents, up to the document,
but hey, it’s just an example)
– If I manually add the paragraph to that same DIV, the “static”
paragraph shows its ID when clicked on, but the “dynamic” one still
shows the DIV ID.
Please, advise?
(also, I need the script to stay at the bottom of my code, so it can “see” all the pics)
EDIT so my point is clearer: I need a way to add content to a DIV so other functions see the new code.
How would you guys replace this line so the sample code works as intended?
$("#DIVnewone").html($txthtml);
Have you tried appending the new element to the div rather than setting it via html(), though I believe .html() should work as well.
then you can use the below ON function (1.7+) to do what you need it to do when you have the mouse over the selector (‘#TXTnewone’). Note that the below will need to go into the “
$(document).ready(function() { ...here... }” function, this is to ensure the “body” tag has been loaded when assigning the on event to it.Here is a jsFiddle of the above working.