How to change right when scrolling on navbar

Asked

Viewed 2,099 times

0

Hi people see if you can help me, I need a function using jquery or a simpler method, which change my logo when scrolling the mouse scroll, at the moment I have the following function, which just changes the color of the navbar:

<script type="text/javascript">
    $(window).on('scroll', function(){
        if($(window).scrollTop()){
            $('nav').addClass('color');
            $('logo').attr('src', '/img/logo-dark.png');
        }else{
            $('nav').removeClass('color');
        }
    })
</script>

Just below I have the html with the logo fixed on that navbar:

 <nav>
    <div id="logo" class="logo">
        <a href="#"><img src="img/logo-branco.png"></a>
    </div>

In this case, every time you scroll down the same scroll in navbar color, change the logo to the logo that is on the site src="img/logo-dark.png"

  • If any answer has served you, mark it as accepted. See how and why in https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

3 answers

1


Follow the script I used on one of my pages

<script>
    $(window).scroll(function () {
        if ($(this).scrollTop() > 50) {
            $('.navbar').css("background-url", "dist/img/logo1.png")
        } else {
            $('.navbar').css("background-url", "dist/img/logo2.png")
        }
    });
</script>

0

You need to use the correct selector on the line:

$('logo').attr('src', '/img/logo-dark.png');

The above selector is incorrect and will not select anything. The correct selector could be:

$('#logo a img').attr('src', '/img/logo-dark.png');

div with id #logo that has the tag a and that has the tag img.

Or:

$('#logo').find("img").attr('src', '/img/logo-dark.png');

div with id #logo that will fetch tags img inside of you.

0

How about putting an id on the image

<img id="image"....

and in the script

$('#image').attr('src',.....

Example:

$(window).on('scroll', function(){
    if($(window).scrollTop()){
        $('nav').addClass('color');
        $('#image').attr('src', 'http://1.bp.blogspot.com/-SAd3nVaqjlE/Tzci2PpZGLI/AAAAAAAAPx4/erFXdQl5MfY/s1600/facebook-wallpaper-celular-papeis+(16).gif');
    }else{
        $('nav').removeClass('color');
    }
})
#enchelinguissa{
height:1200px;
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
    <div id="logo" class="logo">
        <a href="#"><img id="image" src="https://78.media.tumblr.com/avatar_5933d8570bff_128.pnj"></a>
    </div>
    
    
    <nav>
    <div id="enchelinguissa">Essa div e o css não fazem parte da resposta.
 É só para dar scroll para testar o "executar"</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.