mobone mobone - 5 months ago 31
Javascript Question

setinterval not working to change image src

Wondering why the following code will not change my img src. The commented out example works just fine. And the alert triggers every 4 seconds. Replacing the src just wont work inside the set interval function.

$(document).ready(function(){
$(".samples_1_1").on("click", function(){
alert('asdf');
//$(this).attr("src", "../../static/results/samples_1_2.png");
setInterval(function() {
alert('alert 1');
$(this).src("src", "../../static/results/samples_1_2.png");
}, 4000);
});
});

Ian Ian
Answer

Firstly, in the second example you're using .src(), which does not exist. Use .attr() as before. Secondly, the $(this) keyword is now inside it's own function, making it undefined. You'll need to specify the element manually using $(".samples_1_1").attr("src", "../../static/results/samples_1_2.png");