I want to store the function reference in a variable and re use it by calling wherever required. Suppose I have a click bound function like this:
var clickEvent = $('#mode').click(function () {
alert("Hello");
});
And I want to reuse it like this:
//call somewhere
clickEvent();
But it is showing an error clickEvent is not a function, why ?
Keep the snippet inside a function , but even in that case the click event won't be triggered.
var x = function() {
$('#mode').click(function() {
alert("Hello");
});
// on call of this function click event will
$("#mode").trigger('click')
}
x()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="mode"> Click</button>
With only javascript
var x = function() {
var el = document.getElementById('mode')
el.addEventListener('click', function() {
alert('clicked')
})
el.click();
}
x()
<button id="mode"> Click</button>
$('#mode').click(...) doesn't return a function, it returns the value of $('#mode') so that you can chain method, e.g. $('#mode').click(...).change(...).
If you want a name for the handler function, define it separately:
function clickEvent() {
alert("Hello");
}
and then use it in the event binding:
$("#mode").click(clickEvent);
or call it directly:
clickEvent();
Related
I have this function in js:
function one(){
function two() {};
function three() {};
element2.onclick = function {
alert("alert");
}
}
element1.addEventListener("click", one, false)
Along with element1, does the code above listens for the event on element2 all the time as well?
Please check here through 1st button I'm initialize the 2nd button click event using addEventListener(). Run the code then click 1st button after that click 2nd button you'll get alert.
<button id="myBtn1">Button1</button>
<button id="myBtn2">Button2</button>
<script>
function one(){
function two() {};
function three() {};
document.getElementById("myBtn2").onclick = function() {
alert("alert");
}
}
document.getElementById("myBtn1").addEventListener("click", one,false)
</script>
The two() and three() functions are never called. The code that they contain is never executed.
Every time when the element2 is clicked, it'll assigned to a handler and that's a lot of repetition.
$(function(){
$("#selector").on("someevent", function(){
let variable = some_value;
$("#anotherselector").click(function(){
//code involving variable here
if(condition){
$(this).off(reference to click event here);
}
});
});
});
Is there any way to turn off an event from inside its handler? I'm trying to do something like the code above, and I need it to turn off ONLY that specific click event (each click event is different).
To reference the click event, you can simply pass it 'click' and the selector for which to disable the event:
$(function(){
$("#selector").on("someevent", function(){
$("#anotherselector").click(function(){
if(condition){
$('#anotherselector').off('click');
}
});
});
});
let numHandler = 0;
$('#register').click(function () {
let counter = 0;
let num = ++numHandler;
$('#clickme').click(function handler () {
counter++;
console.log(`Handler ${num} clicked!`);
if (counter == 3) $('#clickme').off('click', handler);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clickme">Click me!</button>
<button id="register">Register new handler</button>
You can read more about the off function in the jQuery documentation.
In the following code:
document.getElementById( 'elem' ).addEventListener( 'blur', function() {
myScript();
});
How can I pass the document.getElementById( 'elem' ) object to myScript()? I was thinking of something like the keyword "this," so I can then act on the element in the callback function.
You have four ways to pass the object this
Bind the this object and call the function:
This approach should be used if you need to execute some logic before myScript() execution
function myScript() {
console.log(this.id);
}
document.getElementById('elem').addEventListener('click', function() {
myScript.bind(this)();
});
<button id="elem">Click me!</button>
Call the function myScript using function call:
This approach should be used if you need to execute some logic before myScript() execution
Also read about function Function.prototype.apply().
function myScript() {
console.log(this.id);
}
document.getElementById('elem').addEventListener('click', function() {
myScript.call(this);
});
<button id="elem">Click me!</button>
Pass the function directly:
function myScript() {
console.log(this.id);
}
document.getElementById('elem').addEventListener('click', myScript);
<button id="elem">Click me!</button>
Or pass the object this:
function myScript(element) {
console.log(element.id);
}
document.getElementById('elem').addEventListener('click', function() {
myScript(this); //Here you will need to use the param.
});
<button id="elem">Click me!</button>
Resource
Function.prototype.bind()
Function.prototype.call()
Function.prototype.apply()
Further to the answer from Ele, you should prefer the binding method. As dfsq said in the comment, you can go
element.addEventListener('click', function() {
myScript(element);
}
However, using an anonymous function like this means you won't be able to remove the event listener.
const element = document.getElementById('elem');
// creates a new function instance with element bound as first arg
const eventListenerCallback = myScript.bind(null, element);
element.addEventListener('click', eventListenerCallback);
function myScript(element, event) {
element.setAttribute('data-clicked', 'true');
// remove the event listener once it has been clicked
element.removeEventListener('click', eventListenerCallback);
}
How do I pass a reference of the button I am clicking into the function it triggers?
jQuery('<button class="btn"/>')
.click(function() {
myFunc(this??);
return false;
})
var myFunc = function (this??) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if(jQuery(this??).parent().hasClass('myClass')){
//DO STUFF HERE
}
}
I can't use the class name as there are several of these buttons on my page.
Use myFunc(this). Its correct way to passs the element to your function
Use any other name other than this for your function parameter.
jQuery('<button class="btn"/>')
.click(function () {
myFunc(this);
return false;
});
var myFunc = function (elem) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if (jQuery(elem).parent().hasClass('myClass')) {
//DO STUFF HERE
}
}
No need to pass it in a separate function
jQuery('<button class="btn"/>')
.click(function() {
if(jQuery(this).parent().hasClass('myClass')){
//DO STUFF HERE
}
return false;
})
Remove ?
jQuery('<button class="btn"/>')
.click(function() {
myFunc(this);
return false;
})
var myFunc = function (obj) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if(jQuery(obj).parent().hasClass('myClass')){
//DO STUFF HERE
}
}
this is a reserved word and cannot be used as a variable (which is what you're attempting to do within your myFunc function. Change the name of your variable in your myFunc declaration:
var myFunc = function (myElement) { ... }
Then change your if statement to reflect that change:
jQuery(myElement).parent().hasClass('myClass')
I dont have much knowledge about jquery but a possible solution using Js is
<script>
function onClick1(b)
{
alert(b.parentNode.className);
}
</script>
<div class="divClass">
<button onclick="onClick1(this)">
hello
</button>
</div>
we can pass "this" in the onclick event attribute, which passes the reference object of the element generating the event (in this case button). We then can reference the parentNode of button and its class with className property.
HTML
<div class="myClass">
<button id="btn" class="btnClass">Hi</button>
</div>
JS
$('.btnClass').click(function() {
myFunc(this);
});
var myFunc = function (a) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if(jQuery(a).parent().hasClass('myClass')){
alert();
//DO STUFF HERE
}
}
Check This Example
i am creating an empty div in the javascript DOM. but when i call some function on it, for example,
var hover = document.createElement("div");
hover.className = "hover";
overlay.appendChild(hover);
hover.onClick = alert("hi");
the onClick function isn't working. Instead it displays an alert as soon as it reaches the div creation part of the script. What am i doing wrong?
Try addEventHandler & attachEvent to attach event to an element :
if (hover.addEventListener)
{
// addEventHandler Sample :
hover.addEventListener('click',function () {
alert("hi");
},false);
}
else if (hover.attachEvent)
{
// attachEvent sample :
hover.attachEvent('onclick',function () {
alert("hi");
});
}
else
{
hover.onclick = function () { alert("hi"); };
}
You need to put the onclick in a function, something like this:
hover.onclick = function() {
alert('hi!');
}
The property name is "onclick" not "onClick". JavaScript is case sensitive.
It also takes a function. The return value of alert(someString) is not a function.