In the example below, the "I'm Yellow" <li>
turns yellow on hover, but when you enter something into the input and click "Generate Text," the dynamically appended <li>
doesn't behave the same on hover.
I've tried selecting the appended li's through class and it still doesn't work. There seems to be something about appended elements that I'm not getting. To spare you some time reading the code I'm pretty sure you only need to look at the .hover function.
<body>
<a href="" class="buttn btn btn-secondary">
<div class="" style="background-color: rgb(0, 0, 0); display: inline;"> Hello</div>
</a>
<a href="" class="buttn2">
<div class="btn" style="background-color: aqua; display: inline;"> Bye</div>
</a>
<form class="form-disable">
<br>
<input type="text" id="message2">
<br>
<button id="myButton" type="submit" disabled>Generate Text</button>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="jQueryDrills.js"></script>
</body>
<script>
$(".form-disable").after("<ul class='the-list'><li><h2>Im Yellow</h2></li></ul>");
$("#myButton").click(function(event) {
let theH2 = document.createElement('h2');
let theLI = document.createElement('li');
let $alert = $('#message2').val();
$(theH2).text($alert);
$(theLI).append(theH2)
$(".the-list").append(theLI);
event.preventDefault();
})
$(".the-list > li").hover(function(){
$(this).css("background-color", "yellow");
},function(){
$(this).css("background-color", "white");
}
)
$("#message2").click(function(){
$("#myButton").removeAttr("disabled");
// event.preventDefault();
})
</script>
", {text: "Hello world", appendTo: $myLI})` - and it's good practice to prefix with `$` only those variables which are actually jQuery Objects - not arbitrary Strings. 99.9% of developers as soon as they see `$text` will know its most likely a jQuery wrapper for some DOM Element, perhaps with ID or class "text". Instead, without the prefix - `text` they will know immediately that's a simple String value - by just reading your code.
– Roko C. Buljan May 05 '21 at 03:05