Rinku Rinku - 5 months ago 9
Javascript Question

CSS Selector for anchor with href not ending in '#'

I want to display a loading icon on page loading.

I am using HTML, CSS and JS code.

HTML:

<div class="loader-icon"></div>


JS:

$(window).load(function() {
$(".loader-icon").fadeOut("slow");
});

$('a').click(function(){
$(".loader-icon").fadeIn("slow");
})


and some CSS to display a loading icon for
div.loader-icon
.

It is working fine if I click on any link which redirects to another page. But it does not work when the link does not redirect to another page. Like when I click on the "Back to Top" icon, the loading icon keeps displaying. It does not fade out.

Suppose:

<a href="http://example.com/page/">Page Now</a>
<a href="http://example.com/page/#">Back to Top</a>
<a href="http://example.com/page2/">Page Other</a>


It will work for 'Page Other' but not for 'Back to Top'.

So I want to choose a selector for anchors whose hrefs do not end in '#'. Or is there a better way to do the same thing using a different easy trick?

Answer

Do you have to worry about other URLs including a #? If not, you can do your binding on this selector:

a:not([href*='#'])

That'll only target links that don't include a # in the URL. You can also use this

a:not([href^='#'])

To target any link that doesn't start with #, and

a:not([href$='#'])

For any link that doesn't end with #. Hopefully one of these helps!