Honzis Novák
Honzis Novák

Reputation: 269

js same onclick for different divs

ik, that this is probably simple, but i can't figure it out.

I have 2 different divs .div1 and .div2 How can I add them same function in (2in1)? So i don't have to write it like this:

$(".div1").click(function(){
        $(".webdesign-karta").css("margin-left", "40%");
    });

$(".div2").click(function(){
        $(".webdesign-karta").css("margin-left", "40%");
    });

But I could write it somehow like this (I want to avoid long code):

$(".div1", ".div2").click(function(){
        $(".webdesign-karta").css("margin-left", "40%");
    });

Thanks everyone, have a nice day!

Upvotes: 1

Views: 94

Answers (1)

gavgrif
gavgrif

Reputation: 15509

You almost had it!

$(".div1, .div2").click(function(){
        $(".webdesign-karta").css("margin-left", "40%");
    });

if you want to be more generic you can do it on the div selector itself:

$("div").click(function(){
        $(".webdesign-karta").css("margin-left", "40%");
    });

or create a CSS style rule and add it on the click - which is better because it doesnt add an inline style rule.:

//css
.moveMargin{margin-left:40%}

//js
$(".div1, .div2").click(function(){
        $(".webdesign-karta").addClass("moveMargin");
    });

Upvotes: 1

Related Questions