I have a javascript file which I want to start when a div has been clicked.
I have already this when clicking the div "option_one", an input will be set to "Option 1":
$("#option_one").click(function() {
$("#input").val('Option 1');
});
How can I fire another js file after clicking the div?
I try something with getScript but I couldn't get it working.
Kind regards,
Arie
There is no need to load the calculate.js file on the click event. Just load it with the page load like so:
HTML:
<!--Your page HTML here... -->
<!--Before your closing body tag-->
<script type="text/javascript" src="somefile.js"></script>
<script type="text/javascript" src="calculate.js"></script>
JS:
// This is inside somefile.js
$("#option_one").click(function() {
$("#input").val('Option 1');
// This function is inside calculate.js
calculate();
});
$("#option_one").click(function() {
$("#input").val('Option 1');
$.getScript( "path/calculating.js" )
.done(function( script, textStatus ) {
//Just after the scripts finishes loading you will be able
//to perform/use functionality included on this script
console.log( textStatus );
})
.fail(function( jqxhr, settings, exception ) {
console.log("Triggered ajaxError handler.");
});
});
Related
I'm trying to lazy-load images using the following script (lazy-load.js):
function lazyLoadImage(imgContainers) {
var img = $('<img src="">');
imgContainers.each(function (i, elm) {
img.attr('src', $(elm).data("large"));
img.on('load', function () {
$(this).addClass('loaded');
});
img.addClass('picture');
$(elm).append(img.clone(true));
});
}
$(window).on('load',function () {
var imgContainers = $(document).find(".img-container:not(:has(.loaded))"); // images not loaded yet
lazyLoadImage(imgContainers);
});
The problem is, everything goes well if I load the script using <script></script> tag but when the script is loaded dynamically using jquery $.getscript() the script is not working consistently (i.e. sometimes the onload event is not triggering).
Loading script dynamically:
$.getScript( "path/to/lazy-load.js" )
.done(function( script, textStatus ) {
console.log( "script loaded' );
})
.fail(function( jqxhr, settings, exception ) {
console.log( "script not loaded' );
});
So, why the script is not working consistently??
window.load fires when the window finished loading. It doesn't fire a second time when you load more content via ajax because there is no way to tell for the browser when you will be finished loading additional content. So for all stuff you do via ajax you have to execute all functionality again.
In your case I guess you want these things to happen:
var imgContainers = $(document).find(".img-container:not(:has(.loaded))"); // images not loaded yet
lazyLoadImage(imgContainers);
So I would say put this in a function and just call it when you finish loading the script:
function lazyloadimages() {
var imgContainers = $(document).find(".img-container:not(:has(.loaded))"); // images not loaded yet
lazyLoadImage(imgContainers);
}
$(window).on('load',function () {
lazyloadimages(); // notice this change, put the stuff in an extra function so you can reuse it!
});
$.getScript( "path/to/lazy-load.js" )
.done(function( script, textStatus ) {
console.log( "script loaded' );
lazyloadimages();
})
.fail(function( jqxhr, settings, exception ) {
console.log( "script not loaded' );
// oh no something went wrong, no need to lazyload something here!
});
I'm relatively new to HTML so please bear with me. I'm trying to add a simple javascript function that was already provided to me that grabs images from Flickr to a button. When I click the button, nothing happens. I'm not sure where the error is occuring but I think it has something to do with the function not executing correctly.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>getJSON</title>
<meta charset="utf-8" />
<script src="jquery-3.1.1.min.js"></script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction()
{ //Functions don't need names. This function will simply run when the page loads
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI,
{ // The "$" simply refers to jQuery. This calls the getJSON function that is found inside jquery-3.1.1.min.js
tags: "Baruch College", //Some filter information in the format set by Flickr, who owns the JSON
tagmode: "any",
format: "json"
})
.done(function( data )
{ //Here, a an unnamed function is created made into the event handler for the "done" event... in other words, this is the code that will manifest itself when the getJSON is done.
$.each( data.items, function( i, item )
{
$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
if ( i === 5 )
{
return false;
}
});
});
}
</script>
</body>
</html>
I uploaded the jquery script mentioned in the HTML: http://pastebin.com/2CfRNkvq
You need to specify where the images will be placed after they are retrieved. In the JavaScript code, you can see that for each image, it creates an <img> tag and appends it to the element with id="images".
Just add id="images" to the button element like this:
<button onclick="myFunction()" id="images">Click me</button>
When you click the button, the images will be placed inside the button.
I cannot figure out how to reload the content within this div periodically:
<div id="redditFeed">
<script src="http://www.reddit.com/r/politics/hot/.embed?limit=10&t=all&style=off" type="text/javascript"></script>
</div>
I've tried some jquery, but the closest I've come is reloading the script into the div without executing it. Help would be much appreciated.
You can use $.getScript to load script again.
setTimeout(function() {
$.getScript( "http://www.reddit.com/r/politics/hot/.embed?limit=10&t=all&style=off", function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});
}, 3000);
I have a hidden div which contains my new links:
<div id="links" style="display:none">
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
...
</div>
The links I want to change are in my head:
<head id="myHead">
<!-- My olds links I want to replace -->
</head>
I've tried something like this:
updateLinks();
function updateLinks() {
var str = document.getElementById("links").innerHTML;
document.getElementById("myHead").innerHTML = str;
}
But my head don't receive the new links.
I want to update my links because I download html files and when I try to open them I have ERR_FILE_NOT_FOUND
Can you help me please?
What do you want is a asyncrounous module loader (AMD) like requirejs.
You can load all you files on demand. Using it it's simple to implement a lazy script loader. :)
Would simply loading the new js scripts suffice for your purposes?
You could use the jQuery method getScript to call it for each attribute src of your scripts in your div, like:
$("#links script").each(function() {
var src = $(this).attr("src");
$.getScript( src, function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});
});
Here is your code
$(function() {
updateLinks();
});
function updateLinks() {
var po = document.querySelector('#links script');
var s = document.querySelector('head');
s.appendChild(po, s)
}
The jsFiddle: http://jsfiddle.net/BenoitNgo/6vca82wh/11/
The question has been answered already on this forum.
How to enable chrome extension without clicking it.
I need to perform a certain function from my extension every time i reload a page(no clicking)
is there a way to do it.
My code which contains the on click method
chrome.extension.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.extension.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.extension.lastError.message;
}
});
}
window.onload = onWindowLoad;
and
chrome.extension.sendMessage({
action: "getSource",
source: started(document)
});
To include jQuery:
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
/*all your normal JavaScript (or include as link)*/
</script>
</head>
Using only pure JavaScript you can do this with:
window.onload = function(){/*your JavaScript code*/};
only the code within that function will be immediately executed.
In jQuery you can wrap the code you want executed upon loading of page inside of $(document).ready(function(){, e.g.
$(document).ready(function(){
/*code goes here*/
});
$(document).ready() checks for when a page is loaded enough to have functionality.