Search code examples
javascriptjquerypreventdefault

event.preventDefault stops social media icons from working


<script>
$(document).ready(function(){
$('body').scrollspy({target: "#navbar", offset: 50});   
$("#myNavbar a").on('click', function(event) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({scrollTop: $(hash).offset().top
    }, 2150, function(){
     });
  });
});
</script> 

<nav class="navbar navbar-default navbar-fixed-top">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span> 
      </button>
     
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
    	<ul class="nav navbar-nav">
<li><a href="#section1"><h5><b>Home</b></h5></a></li>
<li><a href="#section3"><h5><b>other</b></h5></a></li> 
<li><a href="#section5"><h5><b>other2</b></h5></a></li>
<li><a href="#section6"><h5><b>other3</b></h5></a></li>
    	</ul>
        <div id="social_nav">
    	<ul class="nav navbar-nav navbar-right">
<li><a href="https://uk.pinterest.com" target="blank"><span class="fa fa-pinterest-square fa-2x"></span></a></li>
<li><a href="https://www.instagram.com" target="blank"><span class="fa fa-instagram fa-2x"></span></a></li>
<li><a href="http://www.facebook.com"  target="blank"><span class="fa fa-facebook-square fa-2x"></span></a></li>
        </ul>
        </div> 
    </div>
  </div>
</nav> 

Hi, I have a bootstrap nav with scrollspy moving smoothly between sections on the page. This uses event.preventDefault(); to stop the page jumping about and is fine. However i have a second part of the nav with social media icons that need to link to a webpage, and these are also stopped from working by event.preventDefault();

Is there a was of stopping event.preventDefault(); for the social media icons but leaving it for the other page nav items please.

Bit of web diy noob so maybe this is easy, but I'm foxed.


Solution

  • You can just exclude the social icons from the event handler

    $("#myNavbar a").not('#social_nav a').on('click', function(event) {
        event.preventDefault();
        var hash = this.hash;
        ....
    });
    

    Should do it, there's no reason to scroll to those icons when clicked, as they redirect anyway.