Disable all links with javascript

Hello,

I want to disable all links that only have a hashtag as href.

The cursor should stay default when hovering over it and there should be no jump when clicking on it.

But normal anchors should still work.

The following code does not seem to work:

jQuery( 'a[href="#"]' ).click(function( event ) {
event.preventDefault();
});

Do you know how I could accomplish that?

  • Kasia Swiderska
    • Support nomad

    Hello flobrunner,

    Your code looks fine – but it could not work because you are attaching it in wrong place. Do you have this code in footer or on header of your site?

    If this is all of your code, then you should have it in the footer. If you want to have it in header of your site, you need to add

    jQuery( document ).ready(function() {
    jQuery( 'a[href="#"]' ).click(function( event ) {
    event.preventDefault();
    });
    });

    if this is not working also, you should check the console in your browser to see if there are any errors.

    Kind regards,

    Kasia

  • flobrunner
    • Design Lord, Child of Thor

    Thanks works perfectly.

    But I’d like this code only to take effect inside of a certain other element:

    <div class="element1">
    <a href="#">test1</a>
    </div>
    <div class="element2">
    <a href="#">test2</a>
    </div>

    And how can I make it that only the link inside “elment1” is affected by the jQuery code above?

    Sorry for the noob questions…

  • Vinod Dalvi
    • WP Unicorn

    Hi flobrunner,

    And how can I make it that only the link inside “elment1” is affected by the jQuery code above?

    You can achieve this using the following modified code.

    jQuery( document ).ready(function() {
    jQuery( '.element1 a[href="#"]' ).click(function( event ) {
    event.preventDefault();
    });
    });

    Best Regards,

    Vinod Dalvi

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.