Mostafa Abedi
Mostafa Abedi

Reputation: 541

How can I detect if a selector clicked?

What is the best way to detect if a jQuery-selector clicked. i mean:

var elem = 'foo'
var action = $(elem ).mouseenter(function(){
$(this).css('background-image',url(elem +'.png'))
});
var elem = 'bar'
//do the same action with new elem
var elem = 'blah'
//do the same action with new elem

the problem is how can i shorten this code to one line:

$('.far').mouseenter(function(){$(this).css('background-image',url(far.png'))});
$('.foooo').mouseenter(function(){$(this).css('background-image',url(foooo.png'))});
$('.bar').mouseenter(function(){$(this).css('background-image',url(bar.png'))});
$('.some').mouseenter(function(){$(this).css('background-image',url(some.png'))});

Upvotes: 2

Views: 386

Answers (4)

alpham8
alpham8

Reputation: 1362

You need something like this:

$(".foo").click(function (event) {
    $(this).css("color", "red");
});

Again, you need click, not mouseenter. Because mouseenter is just a hover, which you could do with plain css.

Upvotes: -3

gurvinder372
gurvinder372

Reputation: 68393

try making this array

var arr = [ "far", "foooo", "bar", "some" ];
arr.forEach( function( item ){
    $('.' + item ).mouseenter(function(){$(this).css('background-image','url('+ item +'.png'))});
    //adding the click detection as well
    $('.' + item ).click(function(){$(this).css('background-image','url('+ item +'.png'))});
});

Upvotes: 2

DarkBee
DarkBee

Reputation: 15634

$(function() {
  $(document).on('mouseenter', 'div[data-background]', function() {
    $(this).css({'background' : 'url('+$(this).data('background')+')',});
  });
});
div {
    width : 500px;
    height : 320px;
    border : 1px solid #A2A2A2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head></head>
<body>
  <div data-background="https://cdn.pixabay.com/photo/2017/04/04/14/23/peacock-2201428_960_720.jpg"></div>
  
  <div data-background="https://cdn.pixabay.com/photo/2013/07/12/18/59/peacock-154128_960_720.png"></div>
  
</body>
</html>

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

Works only in this situation.

Since you have single class selector,assuming you don't have multiple classes

$('.far','.foooo','.bar','.some').mouseenter(function(){
 var selector = $(this).attr('class');
 $(this).css('background-image',url(selector+'.png'));
});

Upvotes: 1

Related Questions