Search code examples
jqueryclassunbinddisable-link

disable click if of <A> if div selected has same id


I have a one page site, and i m sliding divs, the div which is visible has class selected.

E.g if ID ONE has class selected, so link which has href #one shld be disabled.

NOTE: I have multiple LINKS which could point to #one, so want to disable all

<div id="one" class="selected">one</div>
<div id="two">one</div>

<a href="#one" id="linkOne">displays two</a>
<a href="#two" id="linkTwo">displays two</a>

I know its confusing and i m really sorry abt it!

EDIT: Can I get ID 'e.g. ONE' of div selected and find all which has same # 'e.g. #ONE'


Solution

  • This will add a disabled class to all A tags where their href matches the id of any element which has the selected class:

    $(function() {
        $("a").removeClass('disabled');
        $('.selected').each(function() {
            $('a[href=#' + $(this).attr('id') + ']').addClass('disabled');
        });
    
    // If by 'disabled', you mean you want the link not to work, then add this:
    
        $('a.disabled').on('click',function(e) {
            alert('you can\'t do that');
            e.preventDefault();
            return false;
        });
    });
    

    Example here: http://jsfiddle.net/dtxan/4/