The best way to run a function javascript in page load - javascript

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.

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..
}

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>

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>

After adding a new element in the DOM, the element does not recognize old script

I have a problem.After adding a new element in the DOM, the element does not recognize old script and the same function that was in this document, how to solve this problem? how to reload the script
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div id='content'>Content.....</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script src='js/script.js' type='text/javascript'></script>
</body>
</html>
// script.js //
$('#content').click(function(){
$('body').append('<div id="apended">Click me!</div>');
});
$('#apended').click(function(){
alert('click!');
});
When you use .on('click', function (e) {}) function, it works only for existing elements. To handle click event on all selector elements, even for elements which will be added in future, you can use one of these functions:
$(document).on('click', "#appended", function (e) {
// some code code
alert('click!');
});
or:
$("body").delegate("#appended", "click", function () {
// your code goes here
alert('click!');
});
For more information read article about Understanding Event Delegation
Instead of click function You can use :
1.live(old version)
2.delegate
3.on
But , if you want to use click with immutation of delegate function :
var myFn=function(e){
if(e.target.id=='apended'){
alert('click');
}
}
$(document).click(myFn)
Demo :http://jsfiddle.net/abdennour/7cyjV/

Declare function inside the body tag leads to "Function not defined"

I render a java script function inside the body tag of my html. After the java script there is a button which calls this function which is declared by the onclick attribute.
<script type="text/javascript">
function f(caller){
console.log('test');
}
</script>
<button onclick="f(this)" type="button">A button</button>
The problem is that it says "ReferenceError: f is not defined". What am I doing wrong?
The following seems to work just fine:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script type="text/javascript">
function f(caller){
console.log('test');
}
</script>
<body>
<button onclick="f(this)" type="button">A button</button>
</body>
</html>
If you are receiving that error, it is probably from somewhere else other than the code you have provided.
Instead of finding the right location for the script within the body tag I would recommend to use the window.onload, function as well as binding the event yourself using addEventListener() inside the script tags within the head tags were it should be or even in an external .js file.
Give your button an id if you want to use getElementById() to select it, similar to this:
window.onload = function () {
var f = function(caller) {
console.log('test');
};
var myButton = document.getElementById('myButton');
myButton.addEventListener('click', function(){
f(this);
});
};
DEMO - Using window.onload() and addEventListener()
My Problem was that I wrote
<script type="text/javascript" src="........." />
<script type="text/javascript">
function f(caller){
console.log('test');
}
</script>
but it should be with a </script> tag.
<script type="text/javascript" src="........." ></script>
<script type="text/javascript">
function f(caller){
console.log('test');
}
</script>

Categories