jquery :: Why does hover trigger instantly? - javascript

Why does the hover event trigger as soon as the page is loaded?
function showSelector(position) {
alert(position);
}
function hideSelector() {
}
$("#1").hover(showSelector(17), hideSelector);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
sup

Because you're calling the function instead of referencing it.
$("#1").hover(showSelector(17), hideSelector);
// ^^^^
Using showSelector(17) as callback to the hover function will call the function first and then assign it's return value to the hover callback. To solve the issue, you can use anonymous function as callback and then call the function inside it with parameters.
function showSelector(position) {
alert(position);
}
function hideSelector() {}
$("#1").hover(function() {
// Use anonymous function
// Call the function with parameter here
showSelector(17);
}, hideSelector);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
sup

Because you are invoking the function by adding () at the end, what you can do is to pass a anonymous function as the mouseenter callback which can call showSelector with the desired arguments like
function showSelector(position) {
alert(position);
}
function hideSelector() {}
$("#1").hover(function() {
showSelector(17)
}, hideSelector);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
sup

Related

How to send paramenter in jquery syntax function?

i want click the button call function with parameter but i don't know how to write syntax
$(document).ready(function () {
$('#ShowMap').on('click', initialize);
})
function initialize(value) {
alert(value);
}
if change code for code down code work but after load page function called
$(document).ready(function () {
$('#ShowMap').on('click', initialize("test"));
})
how to fix the problem ?
This doesn't send the function as a parameter, it immediately executes the function and sends the result (which is undefined) as the parameter:
$('#ShowMap').on('click', initialize("test"));
Instead, wrap it in a function to be the parameter:
$('#ShowMap').on('click', function () { initialize("test"); });
You can pass another function as argument and inside that function call the desired function
$('#ShowMap').on('click', initialize("test")); will not send function as argument it will send the return value of the initialize which is undefined
function initialize(value){
console.log(value);
}
$(document).ready(function () {
$('#ShowMap').on('click',() => initialize("test"));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="ShowMap">Show Map</button>

How to reference "this" of another parameter passed into function?

Say I have a javascript function for a hover event like this:
hoverFunc = function (HoverElement, AnimatedElement) {
HoverElement.on({
mouseenter: function () {
AnimatedElement.hide();
}
});
}
The tricky part is I want to keep AnimatedElement dynamic, and be able to use it as a reference of HoverElement's "this".
Here's an example of how I'd want AnimatedElement to function:
hoverFunc = function (HoverElement, AnimatedElement) {
HoverElement.on({
mouseenter: function () {
$(this).find("img").hide(); //this being a reference to HoverElement
}
});
}
So I'd like AnimatedElement to be able to be a "this" reference to HoverElement. I've tried writing it like this:
hoverFunc($("div"), $(this).find("img"));
But obviously the "this" will not reference the first parameter. Is there a way to achieve this? Thanks
instead of this use event.target and pass event in mouseenter function call
mouseenter: function (event) {
$(event.target).find("img").hide(); //this being a reference to HoverElement
}
Use bind() to do this
hoverFunc = function (HoverElement, AnimatedElement) {
HoverElement.on({
mouseenter: function () {
$(this).find("img").hide(); //this being a reference to HoverElement
}.bind(HoverElement)
});
}
fnc.bind() Description
From your example,
hoverFunc = function (HoverElement, AnimatedElement) {
HoverElement.on({
mouseenter: function () {
$(this).find("img").hide(); //this being a reference to HoverElement
}
});
}
Here this withing mouseenter event is actually HoverElement's this. As you're binding the mouseenter on HoverElement, so withing event callback this is actually HoverElement.
DEMO

Pass $(this) to a Binded Callback Function

I am trying to understand the difference between these two callback methods and how they handle the $(this) context.
Working Example
$("#container").on("click",".button", function() {
$(this).text("foo");
});
This process works just fine. However, if I want to do a different approach, I lose the context of the event.
Non-Working Example
bindAnEventToAnElement: function(theElement, theEvent, theFunctions) {
$("body").on(theEvent, theElement, function() {
theFunctions();
});
}
bindAnEventToAnElement(".button", "click", function() {
$(this).text("foo");
});
The latter produces an undefined error. Is there a way I can handle callbacks like this while retaining the context of the event?
Fiddle
http://jsfiddle.net/szrjt6ta/
AFAIK, jquery's this in that callback function refers to the event.currentTarget value. So, you should also pass the event object and do something like this:
$("#container").on("click", ".button", function () {
$(this).text("foo");
});
theApp = {
bindAnEventToAnElement: function (theElement, theEvent, theFunctions) {
$("body").on(theEvent, theElement, function (e) {
theFunctions.apply(this /* or e.currentTarget */, arguments);
});
}
}
theApp.bindAnEventToAnElement(".button-two", "click", function () {
$(this).text("foo");
});
Working Fiddle
If I try to explain the problem, jquery is binding the callback function to pass this as e.currentTarget. But you are passing an another callback function inside that callback function whose scope will not be its parent callback function but will be the window. So, you need to again bind the this to the wrapped function, which you can do using apply or call.
You have to manually bind the context to the function in order to have this valorized inside your callback:
$("body").on(theEvent, theElement, function() {
theFunctions.apply(this);
});
example http://jsfiddle.net/szrjt6ta/1/
Find more about apply() here
you can pass the event, then use $(e.target)
https://jsfiddle.net/szrjt6ta/3/
Use .call(this) The call() method calls a function with a given this value and arguments provided individually.
Note: While the syntax of this function is almost identical to that of
apply(), the fundamental difference is that call() accepts an argument
list, while apply() accepts a single array of arguments.
$("#container").on("click",".button", function() {
$(this).text("foo");
});
theApp = {
bindAnEventToAnElement: function(theEvent, theElement, theFunctions) {
$("body").on(theEvent, theElement, function() {
theFunctions.call(this);
});
}
}
theApp.bindAnEventToAnElement("click", ".button-two", function() {
$(this).text("fooe");
});
Fiddle
Change the event handler attachment from
$("body").on(theEvent, theElement, function() {theFunctions();});
to
$("body " + theElement).on(theEvent, theFunctions);
Like this:
HTML:
<div id="container">
<a class="button">Button</a><br />
<a class="button-two">Button Binded</a>
</div>
JQuery:
$("#container").on("click",".button", function() {
$(this).text("foo");
});
theApp = {
bindAnEventToAnElement: function(theElement, theEvent, theFunctions) {
$("body " + theElement).on(theEvent, theFunctions);
}
}
theApp.bindAnEventToAnElement(".button-two", "click", function() {
$(this).text("foo");
});
Fiddle: https://jsfiddle.net/szrjt6ta/10/

why I cannot call outside function from $(document).ready

With below code, click on button doesn't call handleData() function,
if I use anonymous function way (which inside the /* */), it worked.
Can someone explain what the problem is? and how to fix it?
I want to call global function from $(document).ready(...).
<html>
<head>
<script src="js/jquery/jquery-1.7.2.min.js"></script>
<script>
function handleData(data, status) {
$("#p1").text(data);
};
$(document).ready(function() {
$("button").click(function() {
$.get("testAsync?name=value", handleData(data, status));
});
/*
$("button").click(function() {
$.get("testAsync?name=value", function(data, status) {
$("#p1").text(data);
});
});
*/
});
</script>
</head>
<body>
<button>Send an HTTP GET</button>
<p id="p1"></p>
</body>
</html>
The function is being called immediately because you have (arguments) after it.
Since the arguments are in order, just pass handleData alone.
Change the function call from
$.get("testAsync?name=value", handleData(data, status));
to
$.get("testAsync?name=value", handleData);
In the first case you are immediately executing the function.. Just pass in the function pointer and it will work as expected..

Javascript anonymous function vs normal function

What's the difference between:
<script type="text/javascript">
$().ready(function() {
InitialDictionary = new Array();
LoadCurrentValues(InitialDictionary);
$("a[id*=SomeLink]").click(function() {
if (!CompareDictionaries(InitialDictionary))
{
alert('Hello')
}
}
)
})
</script>
and
<script type="text/javascript">
$().ready(function () {
InitialDictionary = new Array();
LoadCurrentValues(InitialDictionary);
$("a[id*=SomeLink]").click(CheckValuesChanged(InitialDictionary));
})
function CheckValuesChanged(InitialDictionary) {
if (!CompareDictionaries(InitialDictionary))
{
alert('Hello')
}
}
</script>
Without going into details into what I'm trying to achieve here, is there any reason why an anonymous method works fine and the call to a function doesn't? Shouldn't they produce the same results?
To call a function you have to do this:
$("a[id*=LogoLink]").click(function(){CheckValuesChanged(InitialDictionary)});
Or:
$("a[id*=LogoLink]").click("CheckValuesChanged(InitialDictionary)"); //might work
They both work, but you cannot bind a function to an event like this
$("a[id*=LogoLink]").click(CheckValuesChanged(InitialDictionary));
because the a function must be bound to the click event. When you pass an argument to the function it returns undefined, which is not a function. You can fix this by changing your second code sample like so:
$().ready(function () {
InitialDictionary = new Array();
LoadCurrentValues(InitialDictionary);
$("a[id*=LogoLink]").click(CheckValuesChanged);
function CheckValuesChanged() {
if (!CompareDictionaries(InitialDictionary)) {
alert('Hello')
}
}
});
The second example is wrong:
$("a[id*=LogoLink]").click(CheckValuesChanged(InitialDictionary));
It should be:
$("a[id*=LogoLink]").click(CheckValuesChanged);
But because you want to pass InitialDictionary as argument you need to use the first approach which will capture it in the anonymous function.

Categories

Resources