WeeklyDad
WeeklyDad

Reputation: 317

Disable anchor with onclick

I have a problem to disable my anchor when its being pressed.

HTML:

<a href='#' data-bind='click: clickActivateSpatialSearch' id='draw_polygon'>
<i class='polygon_mark'></i>
</a>
<a href='#' data-bind='click: clickActivateSpatialSearchBox' id='draw_box'>
<i class='square_mark'></i>
</a>

jQuery

    $('.square_mark').click(function () {
        if(!$(this).hasClass('active')) {
            $(this).addClass('active');
            $('.polygon_mark').off('click', disabler);
        } else {
            $(this).removeClass('active');
            $('.polygon_mark').on('click', disabler);
        }
    });
    $('.polygon_mark').click(function () {
        if(!$(this).hasClass('active')) {
            $(this).addClass('active');
            $('.square_mark').off('click', disabler);
        } else {
            $(this).removeClass('active');
            $('.square_mark').on('click', disabler);
        }
    });
});

Function:

disabler: function(event) {
    event.preventDefault();
    return false;
},

The functionality to change classes are working fine, but what I wanted to add into this, os when anchor #1 is being pressed, this disables the other anchor, and when I press it once again, I'd like it to reenable the anchor, and also the other way around but for anchor #2.

I tried doing something like this, but I cannot get it to work, not fully understanding it either.

Upvotes: 0

Views: 6541

Answers (2)

Martin Turjak
Martin Turjak

Reputation: 21214

Do this and add a disable class to your css.

$('.square_mark').click(function () {
        $(this).toggleClass('active');
        $('.polygon_mark').toggleClass("disabled");
});

$('.polygon_mark').click(function () {
        $(this).toggleClass('active');
        $('.square_mark').toggleClass("disabled");
});

this should do the tric.

.disabled {
   pointer-events: none;
   cursor: default;
}

Edit: example on jsfiddle: http://jsfiddle.net/uKCYN/

And if you need to check for the active class to do something else you can code it like this:

$('.square_mark').click(function () {
    if(!$(this).hasClass('active'))
        $(this).addClass('active');
    else
        $(this).removeClass('active');
    $('.polygon_mark').toggleClass("disabled");
});

$('.polygon_mark').click(function () {
    if(!$(this).hasClass('active'))
        $(this).addClass('active');
    else
        $(this).removeClass('active');
    $('.square_mark').toggleClass("disabled");
});

and add your additional stuff into the if clauses.

Upvotes: 3

palaѕн
palaѕн

Reputation: 73896

Just modify the handler function like this and try again:

// handler function
function disabler(event) {
    event.preventDefault();
    console.log('item anchor clicked');
}

Upvotes: 1

Related Questions