John Wick
John Wick

Reputation: 509

Target element that is being click

Hi I have two click events with class on it, I want to target the only element that is being clicked, lets say for example I want to target two divs with the same class that wouldn't affect the other one.

Here is my code. Thank you.

 $elem.find('.arrow-left').on('click', function (e){
      scrollLeft();
    });

    $elem.find('.arrow-right').on('click', function(e){ 
      scrollRight()         
    });

Basically I have two arrow left class with click event. I just want to target the element that is being clicked

Upvotes: 0

Views: 36

Answers (2)

caldera.sac
caldera.sac

Reputation: 5088

I think this is what you expect. try this

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
	
<input type="button" value="< LEFT" ="" class="mybutton" id="left">
<input type="button" value="RIGHT >" ="" class="mybutton" id="right">

	
</body>

<script type="text/javascript">


$(".mybutton").click(function(){
	var theclickedbuttonId = $(this).attr('id');
	alert("you clicked the :" +theclickedbuttonId +" button");

	//according to the the theclickedbuttonId value, you can do your implementation. as and example 
	if(theclickedbuttonId == "left")
	{

	}
	else
	{

	}
});



</script>
</html>
note : first it check which button click with the same class name and then do the needful

hope this will help to you.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074178

Within the event handler, this will be a reference to the element in question. It refers to the DOM element, so if you want to use jQuery methods on it, wrap it with $(this) first.

From the documentation:

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.) To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).

Upvotes: 1

Related Questions