1

My phpcode is

<?php for($i = 1; $i < 5; $i++) { ?>
  <div class="upperBoxContainer" id="test1<?php echo $i; ?>"> 
    <a href="#"><img id="test<?php echo $i; ?>" src="images/midimages/<?php echo $i; ?>.jpg"></a>
  </div>
<?php } ?>

And my javascript code is

jQuery(document).ready(function() {
    for (var i = 1; i < 5; i++) {
        alert('images/midimageshover/' + i + '.jpg');
        $('#test1' + i).hover(function() {
            $('#test' + i).attr('src', 'images/midimageshover/' + i + '.jpg');
        });
        $('#test1' + i).mouseout(function() {
            $('#test' + i).attr('src', 'images/midimages/' + i + '.jpg');
        });
    }
});

There is some error due to this code is not work. can you please find this.

Thanks in advance

5
  • 2
    At least provide the error message Commented Jul 9, 2013 at 10:18
  • dude, for me the code looks no logical errors, but in place of .hover use .mouseover $('#test1'+i).mouseover (function(){... Commented Jul 9, 2013 at 10:22
  • It'd be much easier to just attach the event handler to the upperBoxContainer and grab the value of $i using jQuery Commented Jul 9, 2013 at 10:25
  • Please provide some form of error message so we can help debug the code. Commented Jul 9, 2013 at 10:34
  • thanks to all! bug removed by Jonathan de M.'s solution Commented Jul 9, 2013 at 13:52

1 Answer 1

1

Enclose your events in a Immediately-Invoked Function Expression (IIFE)

jQuery(document).ready(function(){
  for (var i = 1; i < 5; i++) {  
    (function(i){
      $('#test1'+i).hover(function(){
        $('#test' + i).attr('src', 'images/midimageshover/' + i + '.jpg');
      });
      $('#test1'+i).mouseout(function(){
        $('#test' + i).attr('src', 'images/midimages/' + i + '.jpg');
      });
    })(i);
  }
});

Your code is rewriting the value of $('#test1'+i) until it reaches 4, so at the end of the loop you'll only have $('#test14').

The code above create different scope by using the IIFE hence $('#test1'+i) won't be overwritten, instead you'll have $('#test11'), $('#test12'), $('#test13'), $('#test14')

Here is a demo to demonstrate the difference with your initial code

Sign up to request clarification or add additional context in comments.

1 Comment

+1 didn't realise you had to wrap a loop like that in a function, but I guess if I'm using jquery I wouldn't have done a for loop so have never come across this problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.