Pregunta

How do i change this so that the #animation src only changes if its not already = suit.gif using an if statement can't figure out syntax.

<script type="text/javascript">
    $(function() {
      $("#nav").click(function() {
            $('html,body').animate({  
                scrollTop: $(document).scrollTop()+600
            }, 1000);
                $('#animation').attr('src','images/suit.gif');
      });
    });
</script>
¿Fue útil?

Solución

Try this:

$(function() {
  $("#nav").click(function() {

     $('html,body').animate({  
        scrollTop: $(document).scrollTop()+600
     }, 1000);

     if($('#animation').attr('src') != 'images/suit.gif'){
        $('#animation').attr('src','images/suit.gif');
     }
   });     
 });

Otros consejos

You can use:

$("#nav").click(function () {
    $('html,body').animate({
        scrollTop: $(document).scrollTop() + 600
    }, 1000);
    var src = $('#animation').attr('src').split('/'),
        imgName = src[src.length - 1];
    if (imgName != "suit.gif") {
        $('#animation').attr('src', 'images/suit.gif');
    }
});

You can check the current source of the image by looking at the src attribute, like so:

    var currentSource = $('#animation').attr('src');

Then you can check what it is. If I were you, I'd use a simple regex test to see if it ends with suit.gif, like so:

    var alreadySuit = /suit\.gif$/i.test(currentSource);

Your code would then look like this:

<script type="text/javascript">
    $(function() {
      $("#nav").click(function() {
            $('html,body').animate({  
                scrollTop: $(document).scrollTop()+600
            }, 1000);
            var anim = $('#animation');
            if(!/suit\.gif$/i.test(anim.attr('src'))){
              $('#animation').attr('src','images/suit.gif');
            }
      });
    });
</script>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top