I am trying to add certain javascript files on an event, say click. I am trying to use the Javascript to be used on same event, only if it is triggered. This is because the scripts are slowing down the page load and there is no need for the scripts otherwise.
Can I just move the scripts to the footer and be all set, or do this pro grammatically via loading them only when needed - via event triggering instead? Below is what I have so far:
HTML:
<a id="customId" href="#myLink"></a>
Javascript:
$(document).ready(function() {
//The async addition
var myJS = {
lazyload : function(scriptSrc) {
if(!this.isPresent(scriptSrc)){
var scriptTag = document.createElement('script');
scriptTag.src = scriptSrc;
scriptTag.async = true;
document.getElementsByTagName('head')[0].appendChild(scriptTag);
}
return false;
}
};
//The event trigger needs to do something using the said script
if($('#customId')){
//Approach 1:
var mapEl = document.getElementById("customId");
mapEl.addEventListener("click", customEventHandler, false);
//mapEl.dispatchEvent(event);
//*where
customEventHandler : function(e){
e.preventDefault;
myJS.lazyload('/jsfile.js');
// Update or use link relative #href (not complete path) and use the javascript without navigating out of page.
//e.currentTarget.dispatchEvent(?);
}
//2nd attempt: Adds the script, but not able to trigger event to use JS
$('#customId').click(function(event) {
event.preventDefault();
myJS.lazyload('/jsfile.js');
//Either approach:
//Trigger the custom event to do an actual click after doing the lazy load, using the JS file
(click); $('#customId').trigger('click'); //Is this correct on same element ID
});
}
}
Try using onload event of script element, defining a custom event to prevent recursively calling native click event handler on element
$(document).ready(function() {
//The async addition
var myJS = {
lazyload: function(scriptSrc, id, type) {
// use `.is()` to check if `script` element has `src`
// equal to `scriptSrc`
if (!$("script[src='"+ scriptSrc +"']").is("*")) {
var scriptTag = document.createElement("script");
scriptTag.src = scriptSrc;
scriptTag.async = true;
// use `script` `onload` to trigger custom event `customClick`
scriptTag.onload = function() {
$(id).trigger(type)
};
document.getElementsByTagName("head")[0].appendChild(scriptTag);
}
return false;
}
};
$("#customId").on("click", function() {
myJS.lazyload("jsfile.js", "#" + this.id, "customClick");
})
// do stuff at `customClick` event
.one("customClick", function(e) {
customClick(e.type)
});
});
plnkr http://plnkr.co/edit/Rw4BRAfSYlXXe5c6IUml?p=preview
Related
I have below line of code which simply places a link on the parent page:
<caps:msg textId="createNews"/>
Onclick of the above link 2 functions are getting called:
###func1():
var timestamp;
function func1() {
timestamp = +new Date();
return false;
}
###func2():
function func2(param1,param2,param3,param4){
var win;
var location = window.location.href; // location A
var encodeStringVar = encodeString(param3);
win = window.open(param1+'/struts1.action?param2='+param2+'¶m3='+ escape(encodeStringVar) +'#'+param4,target='t1','toolbar=no,scrollbars=yes,menubar=no,location=no,width=990,height=630, top=100, left=100');
window.location.href = location; // location A
return win;
}
On click of link on parent page, a popup opens by calling struts action, and it works just fine. Only problem is when the link on parent page is clicked, it refreshes the parent page. I don't want it to refresh and I tried adding return false in the link and Javascript void() function, Also I tried by adding an event listener for click event on this link as below:
$(document).ready(function() {
$("#createNewsLink").click(function(event) {
//return false;
event.preventDefault();
})
})
and below:
$(document).ready(function() {
document.getElementById("createNewsLink").addEventListener("click", function(event) {
event.preventDefault();
});
})
But none of these did the trick, can someone please point out the mistake in my code?
Could you consider to try :
(function(){
var linkElement = document.querySelector('#createNewsLink');
linkElement.addEventListener('click',function(e) {
var param1 = e.target.getAttribute('attr-param1');
var param2 = e.target.getAttribute('attr-param2');
console.log(param1,param2);
// Do what ever you want here.
e.preventDefault();
});
})();
Click me
Here i avoid any Event binding from html, and centralize all traitment / binding in one place. Then i point one way to find back mandatory params for your traitment.
I have a script that loads ckeditor.js and once loaded it disables auto inline ..
var script = window.document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'ckeditor.js');
window.document.body.appendChild(script);
script.addEventListener('load', function() {
CKEDITOR.disableAutoInline = true;
});
Is there a way I can assert that CKEDITOR.disableAutoInline is set to true once the script's load event handler is triggered?
it('should ensure disableAutoInline is set to true when the ckeditor.js file is loaded in the browser', function() {
window.CKEDITOR = {
disableAutoInline: false
};
var ckeditorjs = window.document.querySelectorAll('[src=\'/ckeditor.js\']');
expect(ckeditorjs.length).to.equal(1);
});
Need to actually trigger the load event on the script ..
var ckeditorjs = window.document.querySelectorAll('[src=\'/ckeditor.js\']');
window.CKEDITOR = {
disableAutoInline: null
};
var event = new Event('load');
ckeditorjs[0].dispatchEvent(event);
expect(window.CKEDITOR.disableAutoInline).to.equal(true);
I have this function below, however I want to make it work on windows load and show the result without clicking the button.
This is the code I use https://raw.githubusercontent.com/SuyashMShepHertz/indexedDB_sample/master/index.html
How to do this?
$("#getBtn").click(function(){
var type = 'permanent';
var request = db.transaction(["hashes"],"readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event){
$("#result").html("Name : "+request.result.name);
};
});
just put your code in
$( window ).load(function() {
//Code Here
});
If you need it both on click and initially when the page loads, make it a reusable function:
function doTheThing() {
var type = 'permanent';
var request = db.transaction(["hashes"], "readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event) {
$("#result").html("Name : " + request.result.name);
};
}
Then call it from both places you need it:
On page load
On click
To call it on page load, just make sure your script is at the end of the HTML (just before the closing </body> tag; this is best practice unless you have a good reason for doing something else) and call it:
doTheThing();
If you can't put the script at the end of the HTML, you can use jQuery's ready callback instead:
// Concise, but easy to misunderstand:
$(doTheThing);
// Or more verbose but also more clear:
$(document).ready(doTheThing);
(See note below about doing it directly or indirectly.)
To call it on click, hook it up, either directly or indirectly:
// Directly
$("#getBtn").click(doTheThing);
// Or indirectly
$("#getBtn").click(function() {
doTheThing();
});
The only reason for hooking it up indirectly would be to avoid having it receive the event object jQuery will pass it automatically, and to avoid having its return value examined by jQuery to see if it should stop propagation and prevent the default event action.
To avoid creating globals, I'd make sure the entire thing is in a scoping function:
(function() {
function doTheThing() {
var type = 'permanent';
var request = db.transaction(["hashes"], "readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event) {
$("#result").html("Name : " + request.result.name);
};
}
doTheThing();
$("#getBtn").click(doTheThing);
})();
just put it in $(document).ready, like this
$(document).ready(function(){
var type = 'permanent';
var request = db.transaction(["hashes"],"readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event){
$("#result").html("Name : "+request.result.name);
};
});
I've made my own upload library dialog with Semantic UI's modal. I'm trying to integrate this dialog within the Pagedown editor.
var converter = Markdown.getSanitizingConverter();
var editor = new Markdown.Editor(converter);
editor.hooks.set("insertImageDialog", function(callback) {
uploadModal.load(); // The dialog HTML gets loaded asynchronously
$('body').on('selection', '.upload-modal', function(e, src) {
console.log(src);
callback(src);
});
return true; // tell the editor that we'll take care of getting the image url
});
Everything works fine the first time selecting an image from the dialog, but after that it breaks:
Uncaught TypeError: Cannot call method 'removeChild' of null Markdown.Editor.js
According to this SO question it has something to do with defining the event handler multiple times, but I can't wrap my head around it.
Some more info:
The HTML for initializing the modal is loaded asynchronously, here is the JS code:
var uploadModal = (function() {
/**
* Load the upload modal.
*/
this.load = function() {
var $modal = $('.upload-modal');
if ($modal.length) {
// Show the already existing modal.
$modal.modal('show');
} else {
// Get the HTML
var request = $.get(appUrl('admin/upload/modal'));
request.done(function(html) {
// Make the modal.
var $modal = $(html);
$modal.modal({
observeChanges: true,
onApprove: function () {
var upload = $modal.find('.selected.upload'),
src = upload.find('.image > img').attr('src');
// Bind the event listener which will return the upload's source URL
$modal.trigger('selection', src);
return true;
}
}).modal('show');
// Some event handlers here
});
}
};
})();
I load the modal by calling uploadModal.load() and watch whenever an image is selected by attaching the 'selection' event handler.
I have a link like:
test
and a javascript variable:
var t='this';
How can I make the click on the link go to http://www.example.com/'+this using pure javascript?
(so clicking makes a dynamic url that has the variable t at the end)
You could provide your anchor an id:
test
and then:
var t = 'this';
document.getElementById('mylink').onclick = function() {
window.location.href = this.href + t;
return false;
};
obviously if you are putting this script in the <head> section you might need to wait for the DOM to be ready before attempting to attach click handlers:
window.onload = function() {
document.getElementById('mylink').onclick = function() {
window.location.href = this.href + t;
return false;
};
};
If you cannot modify your DOM to provide an unique id to your anchor you could use the document.getElementsByTagName method which will return you an array of all elements with the given tag in your DOM and then you will have to loop through them and attach the onclick handler to your anchor. In order to identify it between all the links that you might have, you will have to use either its innerHTML text or the current href property.
Based on Darin solition, this opens into a new window and does not modify original;
window.onload = function() {
document.getElementById('mylink').onclick = function() {
window.open(this.href + t);
return false;
};
};