function inside click() get executed after setting the element's click method - javascript

<!doctype html>
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<script>
function show1(){
$("#btn").click(show2());
window.alert("1st show");
}
function show2(){
$("#btn").click(show3());
window.alert("2nd show");
}
function show3(){
window.alert("3rd show");
}
</script>
<button id="btn" onclick="show1()">Show</button>
</body>
</html>
I dont understand the behavior of the code above. After setting the $("#btn").click(show2());, the function is executed even though I din't clicked the button. Why?

Since these are callbacks, you need to follow this
$("#btn").click(show2);
or this
$("#btn").click(function(){ show2(); });
Otherwise, if you use show2(), you will invoke the function because it will not be a reference to the function.

You need to pass a function reference as the event handler, in your case you are invoking the handle function and is passing the value returned by it as the handler
$("#btn").click(show2);//no () at the end
Demo: Fiddle

Try like this
function show1(){
$("#btn").click(show2);
window.alert("1st show");
}
function show2(){
window.alert("2nd show");
}
Try to catch event by using .on
function show1(){
$("#btn").on("click",show2);
window.alert("1st show");
}
function show2(){
window.alert("2nd show");
}

Related

How to pass click location to a function as parameter in JS? [duplicate]

so in my html i have this portion:
<body ondblclick="myfunc();">
<div id="id1">dasd</div>
<div id="id2">dasda</div>
</body>
and in javascript the function is :
function myfunc() {
do stuff here...
}
i want to know inside myfunc() on which element of the html body the doubleclick was made, because i don't want to triger myfunc() on every doubleclicked element
so how can i detect the id of the element doubleclicked?
<body ondblclick="myfunc(event);">
function myfunc(e) {
// e.target -> element that was clicked
}
make your HTML as
<body ondblclick="myfunc(event);">
and make myfunc as:
function myfunc(event) {
alert(event.target.id); //here you can get element id that is double clicked
event.stopPropagation();
}
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>ondblclick event example</title>
<script>
function initElement() {
var body = document.getElementById("bdy");
body.ondblclick = showAlert;
}
function showAlert(e){
alert(e.target.id);
}
window.onload = initElement;
</script>
</head>
<body id="bdy">
<div id="id1">dasd</div>
<div id="id2">dasda</div>
</body>
</html>
you can define different events with use of on or bind suppose..
$("#id").on("doubleClick",function () {} );
so it will know that its double click event..
or for javascript you can use like this
<body ondblclick="myfunc(event);">
function myfunc(event) {
do something..
}

The best way to run a function javascript in page load

please don't duplicate me with: $(document).ready equivalent without jQuery
My question have a little difference. I will explain about this.
I has been put all my function on ready funtion like this.
$(document).ready(function () {
$("#liLanguage").find("a").click(function () {
ChangLanguage(this);
});
// orther a lot of function here
LoadDataToGrid();
}
It's done well
But, yesterday my PM said: "you don't need put your code in the ready function, you can run without ready function, put in ready function is very crazy and stupid."
I has been read more topic about ready function and window.onload() function. But no where say that we can't run a function in ready funtion. What's wrong with my code when i put all function in ready funtion?.
This is better
$(document).ready(function () {
$("#liLanguage").find("a").click(function () {
ChangLanguage(this);
});
}
Or this is better( without ready function)
$("#liLanguage").find("a").click(function () {
ChangLanguage(this);
});
Usually, PMs don't have an engineering background and they like to talk like they do. Try to watch for that.
Now to answer your question, you can simply add your script in the bottom of the HTML instead of in the head. That way your script will load after the DOM is ready each is basically what document.ready does.
I think, you put in ready function will better because it's independent where you put your code. For example:
Example 1:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
Test();
});
function Test() {
$("#test").click(function (){
console.log(2);
})
}
</script>
</head>
<body>
<input type = "button" id ="test" value = "Test">
</body>
</html>
But it will not run if you put code like this.
Example 2:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
Test();
function Test() {
$("#test").click(function (){
console.log(2);
})
}
</script>
</head>
<body>
<input type = "button" id ="test" value = "Test">
</body>
</html>
It will run ok if you put your script after html.
Example 3:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type = "button" id ="test" value = "Test">
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
Test();
function Test() {
$("#test").click(function (){
console.log(2);
})
}
</script>
It's mean: with example 1 you can put javascript any where, you don't need to care about it.

Javascript onclick function html

I am trying to customize some public git, and because I am a noob in Jquery/Javascript I do not know how to properly bind an onclick function to the button, so that it will know how to call getStates() function. Yes I know that I could just remove $(function(){ and it would work, but I want to be able to call it within jquery function ?
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>US Hospitals</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox.js/v2.2.3/mapbox.js'>
</script>
<link href='https://api.mapbox.com/mapbox.js/v2.2.3/mapbox.css' rel='stylesheet' />
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="/lib/neo4j-web.min.js"></script>
</head>
<body>
<div id="desc">
<div class="row top-row">
<div class="col-xs-6">
<h3 class="heading">US Hospitals</h3>
</div>
<div class="col-xs-6">
<p class="lead"></p>
</div>
<button onclick="$.getStates();">Load States!</button>
</div>
</div>
<div id='map'></div>
<script>
$(function(){
function getStates() {
session
.run(districtQuery)
.then(function(result){
result.records.forEach(function(record) {
drawPolygons(parseWKTPolygons(record.get("wkt")),
record.get("text"));
});
})
}
</script>
</body>
</html>
I get the error saying :
Uncaught TypeError: $.getStates is not a function
at HTMLButtonElement.onclick (index.html:51)
$(function () { })
This is telling the interpreter to run any JavaScript/jQuery code as soon as the page is ready. This are usually referred to as an onready function. You don't typically create other functions inside of here.
Remove:
$(function () { })
Also, the way you are creating the onclick event is wrong. Use getStates() instead of $.getStates()
So all in all, your code should be changed as following:
<button onclick="getStates();">Load States!</button>
<script>
function getStates() {
session
.run(districtQuery)
.then(function(result){
result.records.forEach(function(record)
{
drawPolygons(parseWKTPolygons(record.get("wkt")),
record.get("text"));
});
});
}
</script>
Another way you could fix it is to leave your onready function and create the click event inside. Your getStates() function still needs to be placed outside of the onready function though and you would remove the onclick from the button element.
For example:
<button>Load States!</button>
<script>
$(function() {
$('button').click(function () {
getStates();
});
});
function getStates() {
session
.run(districtQuery)
.then(function(result){
result.records.forEach(function(record) {
drawPolygons(parseWKTPolygons(record.get("wkt")),
record.get("text"));
});
})
}
</script>
Now if you have more than one button on this page, you will need to add an ID or class to distinguish them. Then you'd replace $('button') with for example: $('#load_states_button) if using an ID or $('.button_class') if using a class.
These all produce the same result, so how to do it is just a matter of personal preference.
Hope this helped! Let me know if you have any questions. :)
You could add an id to the button and use something like this:
<button id="load-states">Load States!</button>
Javascript:
$(function() {
function getStates() {
session
.run(districtQuery)
.then(function(result){
result.records.forEach(function(record) {
drawPolygons(parseWKTPolygons(record.get("wkt")),record.get("text"));
});
})
}
// Adding event onClick to button
$('#load-states').on('click', getStates);
});
You can make the function global:
window.getStates = function getStates() {
...
};
Then you can simply use getStates() in the onclick attribute.
Of course, the cleaner way to do this would be to bind the event from JavaScript itself, using jQuery's $.click(). This would require you to add an id attribute to the button tag, or some other way to identify it from jQuery.
Take the function out of $(function() { ... }), because functions called from onclick have to be in the global scope. And call it as getStates(), not $.getStates()
<script>
function getStates() {
session
.run(districtQuery)
.then(function(result){
result.records.forEach(function(record) {
drawPolygons(parseWKTPolygons(record.get("wkt")),
record.get("text"));
});
})
}
</script>

Unclear behavior of a global variable

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="/jquery-2.1.0.min.js"></script>
<title>Title!</title>
<script type="text/javascript">
var x = false;
function foo() {
alert (x);
return true;
}
window.onload = function() {
$('#my_form').attr('onsubmit', foo);
$('a').click(function(e) {
x = true;
$('#my_form').submit();
return false;
});
}
</script>
</head>
<body>
<form id="my_form" action="">
<input type="submit">
</form>
Click here!
</body>
</html>
The 'a' click function sets the variable x to be true, why it is false when foo() is run?
Raw JS events do not work the same way as jQuery events. Don't mix the two.
attr allows you to supply a function as the second parameter. That is why your code fires immediately. It is simply assigning the return value to the attribute, e.g. onsubmit="true"
Your current fiddle fires the foo handler as soon as you run this line:
$('#my_form').attr('onsubmit', foo)
You probably meant something like this (or equivalent), but it does not work either:
$('#my_form').attr('onsubmit', "javascript:foo()");
Here is the jQuery equivalent:
var x = false;
function foo() {
alert (x);
return true;
}
$(function() {
$('#my_form').submit(foo);
$('a').click(function(e) {
x = true;
$('#my_form').submit();
return false;
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/Lf8hhwvq/
The shortcut DOM ready handler I use above, $(function(){...});, also acts as an IIFE, so you can move the related code inside it:
$(function () {
var x = false;
function foo() {
alert(x);
return true;
}
$('#my_form').submit(foo);
$('a').click(function (e) {
x = true;
$('#my_form').submit();
return false;
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/Lf8hhwvq/1/
There are quite a few problems with this code. First of all, you are mixing old parts of the DOM API with jQuery. In your case I would recommend just to stick to jQuery. Amongst other things:
You should put all render-blocking code (that includes code that changes the DOM) before the </body> Tag, not in the <head>. Depending on the size of your JavaScript dependencies, your page will load very slowly.
Don't use window.load =, especially if jQuery has its very own $(document).ready() function, that probably meets your needs even better.
If you want to set an event handler, don't try to set it with the attr function. That's a very old way of doing it and also the source of your problem. Use the jQuery .on() function instead (the jQuery equivalent of .addEventListener).
If you can avoid it, don't use global variables. Wrap all your code in an IIFE instead.
Thus, your code becomes:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title!</title>
</head>
<body>
<form id="my_form" action="">
<input type="submit">
</form>
Click here!
<script src="/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var x = false;
function foo() {
alert (x);
return true;
}
$('#my_form').on('submit', foo);
$('a').on('click', function(e) {
x = true;
$('#my_form').submit();
return false;
});
});
</script>
</body>
</html>
Codepen: http://codepen.io/anon/pen/zvaOLR

Calling function from Javascript string

$("#showloader").replaceWith("<span class='iconexclaim'><img src='images/backupiconexclaim.jpg' /></span><span class='retry-btn' onclick='abc()'>Retry</span>");
function abc() {
alert("abc");
}
The above code is replacing the html with selected element object, but when I click on retry it is showing function is not defined.
you need to bind the click on the span to the document, this code will help you on that.
$("#showloader").replaceWith("<span class='iconexclaim'><img src='images/backupiconexclaim.jpg' /></span><span class='retry-btn' >Retry</span>");
$(document)
.on(
'click',
'.retry-btn',
function() {
alert("I am here") ;
}) ;
If you wrap the abc() inside your head tag or on body load, it will work:
function abc() {
alert("hi");
$("#showloader").replaceWith("<span class='iconexclaim'><img src='images/backupiconexclaim.jpg' /></span><span class='retry-btn' onclick='abc()'>Retry</span>");
}
$(document).ready(function(){
abc();
});
FIDDLE
You need to put that function code block somewhere (above it) before you call .replaceWith or manipulate the dom.
Please Try like this :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("#showloader").replaceWith("<span class='iconexclaim'> <img src='images/backupiconexclaim.jpg' /></span><span class='retry-btn' onClick='abc()'>Retry</span>");
});
function abc(){
alert("abc");
}
</script>
</head>
<body>
<div id='showloader'>helloo world</div>
</body>
</html>

Categories