Fiddle jQuery is working on older version, but not the recent one?

44 Views Asked by At
` Fiddle link: http://jsfiddle.net/vu6hN/28/ `

Basically, if you expand the window size anything larger than 1230px, you will notice a navigation bar to the right. It's supposed to highlight whichever section you are scrolling on.

For some reason, when I have the jQuery version set to 1.10.1, it works. But when I change it to version 3.4.1 it breaks!

1

There are 1 best solutions below

0
On

You need to wrap #'+ id +' in "" like $('#nav nav a[href="#'+ id +'"]').addClass('active');

Demo

$('#nav nav a').on('click', function(event) {
    $(this).parent().find('a').removeClass('active');
    $(this).addClass('active');
});

$(window).on('scroll', function() {
    $('.target').each(function() {
        if($(window).scrollTop() >= $(this).offset().top) {
            var id = $(this).attr('id');
            $('#nav nav a').removeClass('active');
            $('#nav nav a[href="#'+ id +'"]').addClass('active');
        }
    });
});
* {
    margin: 0;
    padding: 0;
}

#main {
    width: 75%;
    float: right;
}

#main div.target {
    background: #ccc;
    height: 400px;
}

#main div.target:nth-child(even) {
    background: #eee;
}

#nav {
    width: 25%;
    position: relative;
}

#nav nav {
    position: fixed;
    width: 25%;
}

#nav a {
    border-bottom: 1px solid #666;
    color: #333;
    display: block;
    padding: 10px;
    text-align: center;
    text-decoration: none;
}

#nav a:hover, #nav a.active {
    background: #666;
    color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="main">
    <div class="target" id="1">TARGET 1</div>
    <div class="target" id="2">TARGET 2</div>
    <div class="target" id="3">TARGET 3</div>
    <div class="target" id="4">TARGET 4</div>
</section>
<aside id="nav">
    <nav>
        <a href="#1" class="active">Punkt 1</a>
        <a href="#2">Punkt 2</a>
        <a href="#3">Punkt 3</a>
        <a href="#4">Punkt 4</a>
    </nav>
</aside>