Meek Meek - 5 months ago 11
jQuery Question

Enabling and disabling default behaviour on click

I have a list with a header and some items. Clicking the header toggles the visibility of the items.

However, I would like to turn the header into a link, and for larger screen sizes this header shouldn't toggle the visibility of its sub items, but just act like a normal link.

I can't get this part to work. I have added return false/true, but it doesn't work. is there a better way to do this?

js:

var header = $('h3');
var list = $('ul');
var width = $(window).width();

header.click(function() {
collapse(this);
});

var collapse = function (el) {
if ($(window).width() < 699) {
$(el).next().slideToggle();
return false;
} else {
$(el).next().show();
return true;
}
};


JsFiddle.

Answer

Use event.preventDefault(); to ignore link,

Fiddle

header.click(function(e) {
    collapse(this,e);
});

var collapse = function (el,event) {
    if ($(window).width() < 699) {
        event.preventDefault();
        $(el).next().slideToggle();

    } else {
        $(el).next().show();
    }
};

Also, I think the else{..} part won't be required as it anyways navigates to another link address.