mobone mobone - 1 year ago 141
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.

$(".samples_1_1").on("click", function(){
//$(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 Source

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");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download