This question already has answers here:
Using an HTML button to call a JavaScript function
(8 answers)
Closed 8 years ago.
I am trying to create a button that if I press on it my javascript file gets called.
The java script file has many functions so I wasn't sure how to call the functions.
This is how I call the javascript file in my html document.
<script src="sketch2.js">
</script>
Thank you
<script src="sketch2.js">
</script>
this is how you include a javascript file in html. to call all the functions in it, make a function which would call all those functions and call this function on button click.
Then add an inline script containing a Javascript function to call the functions
<script>
function newfunction(){
fun1();
fun2();
...
}
</script>
Then in the HTML you need
<button onclick="newfunction()">click here</button>
Do it like below:
<a href='linkhref.html' id='mylink'>click me</a>
<script type="text/javascript">
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "Public/Scripts/filename.js.";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
</script>
Create a Button and bind your javascript function to the onclick event. Like this:
<button onclick="functionCall()">
Do Something
</button>
But you cant just call the whole script file. Ask yourself this question: how should the browser know, which method to call.
In my litte example, it worked:
<html>
<head>
<script>
function functionCall(){
alert('hi');
}
</script>
</head>
<body>
<button onclick="functionCall()">Do Something</button>
</body>
</html>
HTML like this:
<button id="myButton">Click me</button>
Save this in your Javascript file, include the script at the bottom of the html page:
(function () {
document.getElementById("myButton").onclick(function () {
// do whatever it is you want to do after the button's been clicked
});
}());
It shall work regardless of what JS Library you happen to be using (if any)
This can all be simply handled in require.js, but here is a very simple implementation.
<div id="btn">Click to load</div>
var btn = document.getElementById('btn');
var loaded = false;
btn.addEventListener('click', function(e) {
if(loaded) return;
loaded = true;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'sketch2.js';
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(script, first);
if(window.addEventListener) {
script.addEventListener('load', function(e) {
// now you can access the functions inside the JS file
});
} else {
script.onreadystatechange = function() {
if(this.readyState === "loaded" || this.readyState === "complete") {
// access the functions in the JS file
script.onreadystatechange = null;
}
};
}
});
$(" the id or class of the button ").click(function(e) {
var url = "(your url)sketch2.js";
$.getScript( url, function() {
//function or something..
});
This is you are looking for:
<div class="whatever" onclick="yourfunction()" >Your Button</div>
Related
I have some simple code like this:
JS:
function load (element, url) {
element.innerHTML = '';
fetch(url).then(function (resp) {
return resp.text();
}).then(function (content) {
element.insertAdjacentHTML('afterbegin', content);
});
}
Content of url parameter of load function:
<div>
<button id="some-button">Execute click!</button>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('some-button').addEventListener('click', function () {
alert('Click at button has been executed.');
});
});
</script>
My question is: Why click event (or any other JS code) does not work? HTML content is loaded, script tag also do, but JS code does not executing. I just want to replace jQuery function load with custom function load described above.
Thanks in advance!
I think JS code included like that does not get recognized as JS code. I mean, text containing <script> tag is not considered as JS code and not run. Tried the following and it seems to work. Not sure if this solves your requirement, but it might help you understand the issue. Note the usage of document.createElement('script')
<div id="content"></div>
<script>
var scr = `document.getElementById('some-button').addEventListener('click', function () {
alert('Click at button has been executed.');
});`;
var content = `<div><button id="some-button">Execute click!</button></div>`;
document.getElementById('content').insertAdjacentHTML('afterbegin', content);
var sel = document.createElement('script');
sel.text = scr;
document.getElementById('content').appendChild(sel);
</script>
Here is final working code:
fetch(url).then(function (resp) {
return resp.text();
}).then(function (body) {
element.insertAdjacentHTML('afterbegin', body);
let scripts = element.getElementsByTagName('script');
for (let scr of scripts) {
var scriptContent = scr.innerText;
var newScript = document.createElement('script');
newScript.text = scriptContent;
scr.remove();
element.appendChild(newScript);
}
});
I would like to display a loader icon gif until the script is totally loaded, is it possible?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<img src="loading.gif">
I think it is necessary to use jquery. but I do not know how to do. could someone help me?
Display image <img src="loading.gif">
On dom-ready remove element.
$(document).ready(function () {
$('img').remove();
})
Can be done even without jQuery:
<img id="loading" src="loading.gif">
<script onload="javascript:document.getElementById('loading').style.display='none'" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
Yes you can. You can use this function which loads a script and fires a callback. In your callback, you hide the gif.
function loadScript( url, callback) {
var script = document.createElement( "script" )
script.type = "text/javascript";
if(script.readyState) { //IE
script.onreadystatechange = function() {
if ( script.readyState === "loaded" || script.readyState === "complete" ) {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function() {
callback();
};
}
script.src = url;
document.getElementsByTagName( "head" )[0].appendChild( script );
}
So, in your HTML place your gif showing up initially. And, add this code at your onload function:
<script>
window.onload = function(){
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js', function(){
$('.gif-selector').hide();
})
}
</script>
Edit: This is a more complex solution than others provided, maybe if your goal is something pretty simple you should use some of the others. Still, this function works great and I have used it in many of my projects. It's best thing is that you can chose to load the script whenever you want to
I am trying to include jquery dynamically and i have used the following code-
index.php
<!doctype html>
<html>
<head>
<script type="text/javascript" src="includejquery.js"></script>
</head>
<body>
<div id="testing"></div>
<script type="text/javascript">
$(document).ready(function(){
$('#testing').html('<p>This is a paragraph!</p>');
});
</script>
</body>
</html>
includejquery.js
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.async = true;
script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
jQuery.noConflict();
}
But jquery functionality is not working it is not printing the paragraph tag :-( Please help me out. Thanks in advance
That's not working because your $(document).ready(... line runs before jQuery loads, and so it fails because either $ is undefined (throwing a ReferenceError) or it refers to something other than jQuery. Also, you're calling jQuery.noConflict() before jQuery is loaded, and if that call did work, it would mean that $ no longer referred to jQuery at all, so $(document).ready(... still wouldn't work.
In any modern browser, you can use the load event on the script element you're adding, which tells you that the script has been loaded. Probably best to pass a callback into a call you make to includejquery.js, like this:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="includejquery.js"></script>
</head>
<body>
<div id="testing"></div>
<script type="text/javascript">
includejQuery(function($){
$('#testing').html('<p>This is a paragraph!</p>');
});
</script>
</body>
</html>
includejquery.js:
function includejQuery(callback) {
if(window.jQuery)
{
// jQuery is already loaded, set up an asynchronous call
// to the callback if any
if (callback)
{
setTimeout(function() {
callback(jQuery);
}, 0);
}
}
else
{
// jQuery not loaded, load it and when it loads call
// noConflict and the callback (if any).
var script = document.createElement('script');
script.onload = function() {
jQuery.noConflict();
if (callback) {
callback(jQuery);
}
};
script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
}
Changes there:
In includejquery.js, just define a function and wait to be called.
Have that function accept a callback.
Have it wait for the script to load.
When the script is loaded, call jQuery.noConflict and then, if there's a callback, call it and pass in the jQuery function.
In the HTML, I'm calling the function, and receiving the argument it passes me as $, so within that function only, $ === jQuery even though outside it, it doesn't (because of noConflict).
What's wrong with the implementation from the HTML5-Boilerplate?
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery_2.1.1.min.js"><\/script>')</script>
Alternative solution
(function () {
initScript().then(function (v) {
console.info(v);
var script = document.getElementById("__jquery");
script.onload = function () {
$(document).ready(function () {
// Main logic goes here.
$("body").css("background-color","gray");
});
};
});
function initScript() {
promise = new Promise(function(resolve,reject) {
try {
if(typeof jQuery == 'undefined') {
console.warn("jQuery doesn't exists");
var jQuery_script = document.createElement("script");
jQuery_script.src = "https://code.jquery.com/jquery-2.2.4.min.js";
jQuery_script.type = 'text/javascript';
jQuery_script.id = "__jquery";
document.head.appendChild(jQuery_script);
resolve("jQuery added succesfully.");
}
resolve("jQuery exists.")
} catch (ex) {
reject("Something went wrong on initScript() : ", ex);
}
});
return promise;
}
})();
I used promise because if there is no jQuery in the page we need to wait to load it first.
.ready will not fire since your script loads async.
This should the first thing to run on the page and block all other scripts in order to load the dependencies on time.
Appending to body:
function loadScript() {
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.mydomain/myscript.js';
script.async = true;
document.body.appendChild(script);
}
Appending to head:
function loadScript() {
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.mydomain/myscript.js';
script.async = true;
head.appendChild(script);
}
Usually when you include some scripts, browser will load them synchronously, step by step.
But if you set
script.async = true;
script will load asynchronously and other scripts will not waiting for them. To fix this problem you can remove this option.
There is an onload event on the script. Use that.
<!doctype html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
script.onload = function() {
$('#testing').html('<p>This is a paragraph!</p>');
};
};
</script>
</head>
<body>
<div id="testing"></div>
</body>
</html>
Check your browsers js console. You will probably see something like $ is undefined and not a function. It is because you are running the code in
You can try to wrap the jquery code you want to run in the readyStateChange event of the script tag. Or you can use require.js.
There is a working demo http://jsbin.com/lepapu/2/edit (Click "Run with JS")
<script>
if(!window.jQuery)
{document.write('<script src=http://code.jquery.com/jquery-2.1.1.min.js><\/script>')}
</script>
<script>
$(document).ready(function(){
$('body').html('<p>This is a paragraph!</p>');
});
</script>
The order of scripts matters.
From below code I am trying to load javascript file TestJScript.js dynamically and after loading want to call javascript function LoadData() exist in that file. But I am getting error please check image.
Note: Error get only on IE-8.0.6001 update 0.
Please suggest me correction such that It will work from 6 to all version of IE.
Or any another solution.
if it require any windows updates. Please let me know.
Please don't suggest with JQUERY code
Javascript file code :
function LoadData() {
alert('ok');
}
Code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function LoadJSFile() {
var js = document.createElement("script")
js.setAttribute("type", "text/javascript")
js.setAttribute("src", "C:\\TestJScript.js")
document.getElementsByTagName("head")[0].appendChild(js)
//call below function exist in TestJScript.js file
LoadData();
}
</script>
</head>
<body onload="LoadJSFile();">
</body>
</html>
Error Image:
Try this http://dustindiaz.com/scriptjs.
Like this:
$script('yui-base.js', function() {
// do stuff with base...
$script(['yui-anim.js', 'yui-connect.js'], function() {
// do stuff with anim and connect...
});
$script('yui-drag.js', function() {
// do stuff with drag...
});
});
The error reports a problem in the javascript file that you're loading. So the problem lies not in how you dynamically load the javascript file, but in the javascript file itself.
It looks like there is a problem with the file once it has loaded. Are you sure there is no syntax error in the file itself.
Also, I would recommend you use a relative path to the javascript file instead of the absolute path.
EDIT:
Try this:
function LoadJSFile() {
var script = document.createElement('script');
script.src = "C:\\TestJScript.js";
script.onload = function () {
LoadData();
};
document.getElementsByTagName("head")[0].appendChild(script)
}
You could try the following:
<script>
function LoadJSFile(src, callback) {
var js = document.createElement('script');
js.src = src;
js.async = true;
js.onreadystatechange = js.onload = function() {
var state = js.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(js);
}
LoadJSFile('C:\\TestJScript.js', function() {
LoadData();
});
</script>
If you are using c# code then another solution to solve this script error is, invoke script through c# code.
Code:
/
/Assiging html value to control
webBrowser.DocumentText = "HTML content";
//Calling document load completed event
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlDocument htmlDocument = webBrowser.Document;
HtmlElement htmlElementHead = htmlDocument.GetElementsByTagName("head")[0];
HtmlElement HtmlElementScript = htmlDocument.CreateElement("script");
HtmlElementScript.SetAttribute("text", "C:\\TestJScript.js");
htmlElementHead.AppendChild(HtmlElementScript);
htmlDocument.InvokeScript("LoadData");
webBrowser.DocumentCompleted -= webBrowser_DocumentCompleted;
}
I am testing with pure JavaScript if browser seems to support HTML5 and if so, I want to load jQuery and then process the rest of page. If not, some redirection will occur.
<script type="text/javascript">
var canvas = document.createElement('canvas');
if (canvas && canvas.getContext && canvas.getContext('2d')) {
var s = document.getElementsByTagName('script')[0];
var jq = document.createElement('script');
jq.type = 'text/javascript';
jq.src = 'js/jquery.js';
s.parentNode.insertBefore(jq, s);
}
else {
// ... redirection ...
}
</script>
<script type="text/javascript">
$(function () {
//...
}
</script>
But the code above is not working properly, because I got error
Uncaught ReferenceError: $ is not defined
which is clearly saying that jQuery library has not been loaded.
Why? What is wrong with conditional script loading in my code above?
This is a case where it may make sense to use document.write(). You'd need to put this code in the <body> instead of the <head>:
<script type="text/javascript">
var canvas = document.createElement('canvas');
if (canvas && canvas.getContext && canvas.getContext('2d')) {
document.write( '<script src="js/jquery.js"><\/script>' );
}
else {
// ... redirection ...
}
</script>
<script type="text/javascript">
$(function () {
//...
}
</script>
Or, you may be able to use an ordinary <script> tag to load jQuery, but put it after your conditional redirection:
<script>
var canvas = document.createElement('canvas');
if( !( canvas && canvas.getContext && canvas.getContext('2d') ) ) {
// ... redirection ...
}
</script>
<script src="js/jquery.js"></script>
<script>
$(function () {
//...
}
</script>
With either of these approaches, the order of execution is:
The first <script>.
The loading of jquery.js, whether done with document.write() or a simple <script> tag.
The final script.
When you insert a script tag like you are, it will be loaded in the background, not immediately and thus your next script will run before jQuery is loaded. You will need to attach a listener such that you know when jQuery is successfully loaded and you can then run your scripts that use jQuery.
Here's an article that describes how to know when a dynamically loaded script is loaded: http://software.intel.com/en-us/blogs/2010/05/22/dynamically-load-javascript-with-load-completion-notification.
FYI, in your specific case, you also could just have a static script tag that loads jQuery, but place your script that detects whether to redirect or not BEFORE the jQuery script tag. That would be the simplest option.
<script type="text/javascript">
var canvas = document.createElement('canvas');
if (!canvas || !canvas.getContext || !canvas.getContext('2d')) {
// redirect here or whatever
}
</script>
<script type="text/javascript" src="jquery.js">
</script>
<script type="text/javascript">
$(function () {
//...
}
</script>
finally working like a charm, I'm relieved myself !
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script type="text/javascript">
window.onload = function(){
var jqu = "$(console.log('worked'));";
var canvas = document.createElement('canvas');
if (canvas && canvas.getContext && canvas.getContext('2d')) {
var s = document.getElementsByTagName('head')[0];
var jq = document.createElement('script');
jq.setAttribute('type','text/javascript');
jq.innerHTML = jqu;
var jqLoad = document.createElement('script');
jqLoad.setAttribute('type','text/javascript');
jqLoad.setAttribute('src','jquery-1.10.0.js');
jqLoad.setAttribute('id','jqloader');
s.appendChild(jqLoad);
document.getElementById('jqloader').onload = function(){
console.log('loaded');
s.appendChild(jq);
}
}
else {
// ... redirection ...
}
console.log(document);
}
</script>
</head>
<body>
</body>
</html>
jsbin Demo
explanation :
1- using dom functions to append or insert elements are always the best (dynamic and safer more than anything else), and document.write is not recommended over that.
2- at parse-time, whatever functions you have in your script will be evaluated thus you will get an error if you have the script and not loaded the library yet.
3- loading the library and executing the relevant script in the same tag is not recommended. better do the script in another tag (after loading is done completely) to ensure it will work.
4- events for document.onload ensures that the document is loaded and the doms exist so you can append children to them. as for the document.getElementById('jqloader').onload it was just to insure that the jquery library is loaded completely and added to the document, and only then the script will be added after and evaluated.
As others have said, the reason you're getting an error is because you've loaded jQuery asynchronously and it hasn't loaded yet.
There are two ways to accomplish what you want.
You can poll for window.jQuery, or you can use an asynchronous loader callback.
Since you only load jQuery only when you detect canvas support, you won't have to worry about supporting old browsers.
var async_script_load = function (s, callback) {
var script;
script = document.createElement("script");
script.async = "async";
if (s.scriptCharset) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function () {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if (head && script.parentNode) {
head.removeChild(script);
}
// Dereference the script
script = undefined;
callback(200, "success");
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore(script, head.firstChild);
};
async_loader({url:'http://tempuri.org/jquery.min.js'},function() {
//call jquery here.
});
For a polling method, it's as simple as:
var checkJq = function() {
if(window.jQuery) {
//do jQuery
} else {
setTimeout(checkJq,100);
}
}
setTimeout(checkJq,100);