Matei Panchios
Matei Panchios

Reputation: 333

JavaScript that adds behavior to all links should exclude some

I have the fallowing smooth scrolling script:

<!-- Smooth scroll JS -->
<script type="text/javascript">
jQuery('a[href^="#"]').click(function(e) {

    jQuery('html,body').animate({ scrollTop: jQuery(this.hash).offset().top}, 1000);

    return false;

    e.preventDefault();

});
</script>

The problem is that it affects all link to an id (as intended) and causes a conflict with toggle script.

I need to add a condition to the script so that the links in the #work_tabs div are not affected.

        <div id="work_tabs">
             <ul>
              <li><a href="#films" class="navLink">Films</a></li>
              <li><a href="#tv_films" class="navLink">TV Films</a></li>
              <li><a href="#tv_shows" class="navLink">TV Shows</a></li>
              <li><a href="#special_events" class="navLink">Special Events</a></li>
            </ul> 
        </div>

I tried adding the condition myself but i'm still new to JS and have no idea how to achieve this.

How could I make the script ignore the links in the work_tabs id?

Upvotes: 1

Views: 54

Answers (3)

Joy Biswas
Joy Biswas

Reputation: 6527

You can use the jQuery .not() function to remove the intended elements

Use jQuery('a[href^="#"]').not('#work_tabs > a')

<!-- Smooth scroll JS -->
<script type="text/javascript">
jQuery('a[href^="#"]').not('#work_tabs > a').click(function(e) {

    jQuery('html,body').animate({ scrollTop: jQuery(this.hash).offset().top}, 1000);

    return false;

    e.preventDefault();

});
</script>

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

One way to go about it is add a class to the items that can be toggled and change your element selector to point to that.

jQuery('.toggle').click(function(e) {

Upvotes: 2

Chrillewoodz
Chrillewoodz

Reputation: 28328

You can use the not() function:

jQuery('a[href^="#"]').not('#work_tabs > a').click(function(e) {

    jQuery('html,body').animate({ scrollTop: jQuery(this.hash).offset().top}, 1000);

    return false;

    e.preventDefault();

});

This will exclude any anchor tags inside that div.

Read more here.

Upvotes: 4

Related Questions