Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect specific element is clicked?

Please follow these two steps:

  • focus on the input by clicking in it
  • and now click on the button

$("input").on({
    focusout: function() {
    	this.value += "one|";
    }
});

$("button").on("click", function(){
  $old_val = $("input").val();
  $("input").val($old_val+"two|");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button>Add "two"</button>

The result will be: one|two|! Well I don't want this. I want to disable focusout when I click on the button. How can I do that?

Expected result after following those two steps should be two|.

like image 738
Martin AJ Avatar asked Jan 20 '17 15:01

Martin AJ


People also ask

How do you know which element is clicked?

To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.

How do you get a clicked element class?

To find the class of clicked element, we use this. className property. The className property is used to set or return the value of an element's class attribute. Using this property, the user can change the class of an element to the desired class.

Which event is run when an element is clicked?

The onclick event occurs when the user clicks on an element.

What is this function in JavaScript?

What is this? In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.


1 Answers

You want to prevent the button from calling the default mousedown event which is where browsers change the focus. Using e.preventDefault() will stop this from happening if you assign it to the mousedown event on the button.

$("input").on({
    focusout: function() {
    	this.value += "one|";
    }
});
$("button").on("mousedown", function(e) {
  e.preventDefault(); 
});
$("button").on("click", function(){
  $old_val = $("input").val();
  $("input").val($old_val+"two|");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button>Add "two"</button>
like image 199
Chase Avatar answered Sep 30 '22 17:09

Chase