-1

i am using this code to open all the URLs in new tab. but i want the url with # do not open in new tab. for example:

jQuery("a").attr("target", "_blank");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<a href="#">content</a>
<a href="#contact">Contact</a>

Thanks

Aman Kumar
  • 4,533
  • 3
  • 18
  • 40
Sajjad Ahmad
  • 143
  • 3
  • 17

2 Answers2

0

You can check working fiddle jsfiddle.net/bharatsing/t0fkzL5p/

$("a").click(function(){
    var href=$(this).attr("href");
  if(href!="" && href!="#"){
    $(this).attr("target", "_blank");
  }
  else{
    return false;
  }
});
Bharatsing Parmar
  • 2,435
  • 1
  • 9
  • 18
0

You can check the href attribute value before appending _blank.

jQuery("a").attr("target", function() {
  if ($(this).attr('href') != '#') {
    $(this).attr('target', '_blank');
  }
});

In the above code, we check for the href value, if it's # then ignore it, else append _blank value to the elements target.

Demo


If you are looking to ignore all a tags where href starts from #, you can do something like

jQuery("a").attr("target", function() {
  if ($(this).attr('href')[0] != '#') { //checks for the first char, if #, ignore
    return '_blank';
  }
});

Demo

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278