user1556393
user1556393

Reputation: 1

click to add border to div

I have a web page with multiple div. When the user clicks on the body, all div elements will have their border changed to red. However, when the user clicks on a div, only that div will have their border changed to blue.Every other div element will remain with a red border. this is my code so far:

$('body').click(function() {
    var $target = $(event.target);
    if (!target.closest($('div')).length) {
        //I want the border of all div on the page to change to red
        $('div'). css('border', '2px solid red');
    } else if (target.closest($('div')).length) {
        //Here just the div that was clicked on will have its border changed to blue
        $(this).css('border', '2px solid blue');
    }
});

Upvotes: 0

Views: 3668

Answers (4)

Zoltan Toth
Zoltan Toth

Reputation: 47677

Try this - http://jsfiddle.net/74pzJ/4/

$('body').on("click", function(e) {
    $("div").css('border', '2px solid red');
    $(e.target).closest("div").css('border', '2px solid blue');
});

Documentation

Upvotes: 3

hkulekci
hkulekci

Reputation: 1942

You can use the following code for to highlight the html tags like firebug. Maybe this is helpful for you.

    document.getElementById('clickable_content').addEventListener("mouseover", function(e) {
        e.stopPropagation();
        e.target.addEventListener("mouseout", function (e) {
            e.target.className = e.target.className.replace(new RegExp(" highlight\\b", "g"), "");
        });
        e.target.addEventListener("click",function(e){
            alert(e.target.className); // clicked div or what ever
        });
        e.target.className += " highlight";
    });

Upvotes: 0

aquinas
aquinas

Reputation: 23796

$('body').click(function() {
    $('div').css('border', '2px solid red');    
});

$('div').click(function(e){
    $(this).css('border', '2px solid blue');
    e.stopPropagation();
});
​

Upvotes: 0

Piyush Sardana
Piyush Sardana

Reputation: 1758

you need to use event.stopPropagation() method here of jquery..in your function

because your click event is bubbling up to other divs

Upvotes: 0

Related Questions