Search code examples
jquerycsspreventdefaultjquery-1.9

jquery: remove the pointer cursor?


Why can't I change the CSS of an a tag with jquery? For instance,

html,

<a href="#">1</a>
<a href="">2</a>
<a href="http://website.com/#/home/about/">3</a>
<a href="http://website.com/home/about/">4</a>

link 1 and 2 are not clickable so I want to remove the pointer cursor.

jquery,

$("a").click(function(e){
    if($(this).attr("href") == "#" || $(this).attr("href") == "") {
        alert("this is non-clickable");
        $(this).css({cursor:"default"});
        e.preventDefault();   
    }
    else{
        alert($(this).attr("href"));
        $(this).css({cursor:"pointer"});
        e.preventDefault();   
    }
});

is it possible?

jsfiddle


Solution

  • If you want you can simply do this with the CSS

    a[href="\#"], a[href=""] {
        cursor: default;
    }
    /* I've used an element[attr] selector here which will select all a tags 
       with this combination, if you want to target specific a tags, 
       wrap them in an element with a class and you can than refer as 
       .class a[href]... */
    

    Demo

    If you want to disable the links, you can achieve that too using CSS pointer-events: none; property

    Demo 2 (Will help you if JS is disabled, this won't alert the message, but it will help you to disable the event which you are trying to do)