I would like to dynamically load a javascript file and undo what was done with the static javascript i have on my site. the static javascript i want to edit is
document.getElementsByTagName('script')[3]this is what im trying to do:
document.getElementsByTagName('script')[3].attributes[2].value = "http://differentlocation.com/jsfile.js"
The thing is when the source is altered I want all the other functions i had statically cached to go away. how is this possible?
*reworded. The sites current javascript attaches event handlers and does all kinds of functions, i would like to make all of these go away. Basically I am reloading a Almost exact copy of the javascript and dont want certain handlers active. etc
Or is there a way to blank out all of the pages current javascript, Just make it all useless, and then Load my new javascript
It looks like you're not using jQuery. If you were, this simple line of code should remove all event handlers from every element in your document:
$("*").off();
It might be worth exploring.
I'm unable to get the JavaScript to run again, most likely: it needs to be linked (which jsFiddle doesn't allow). Here's a demo.
In this example, we have three buttons.
<button id="myButton">Add an event listener for the bellow</button>
<button id="listener">Do something</button>
<button id="reset">reset</button>
We can then add event listeners,
// Do some stuff
document.getElementById("myButton").addEventListener("click", function () {
document.getElementById("listener").addEventListener("click", function () {
alert("I do something!");
});
});
... and at some point, reset the page. This works by taking the current HTML content out of the page, and having it stored in a variable. We then put it back in, causing all bindings to elements to be removed. It also has the harmful side effect of not running inline scripts.
// Soft reload of the page
document.getElementById("reset").addEventListener("click", function () {
var html = document.documentElement.innerHTML;
document.documentElement.innerHTML = "";
document.documentElement.innerHTML = html;
});
Related
Is there a way to disable the onclick function but still use the href to re-direct the user to the requested link. Example a header menu there are many links that looks like below :
Phones
I am unable to remove the "DA_A('id', ':per:shop', this.href); return false;" from the HTML page. However using a tag manager how would one go about injecting a snippet of JavaScript code function which will de-activate/mute the "DA_A" function but still make the link work as normal? Is it possible? It seems the function "DA_A" is a function that calls another ".push" function and pass some data.
What are my options? as I am unable to edit the menus in questions?
You can probably remove the onclick from the element if you can run some javascript after the DOM renders:
var anchor = document.getElementById("someId"); // or tagname, querySelector, etc
anchor.onclick = "";
You could also disable the function it calls altogether, depending on whether it is needed elsewhere:
window.DA_A = function() { /* do nothing */ };
The first snippet would need to be run after the DOM was rendered (for example, if you are using jquery then enclose it in a $(function() {})), and the second snippet would need to run after the DA_A function is defined in the first place.
Either of these by themselves should disable the onclick, but still allow the anchor to navigate.
this code snippet will do the trick:
window.onload = function()
{
document.querySelctor("a").removeAttribute("onclick"); // make selector more specific
};
I have a page that forces some JS to load on a page that I need to override. I can load a separate JS file to do this. I want to have the page do the .show for any of the .below-the-folds on the page. I guess the best way to say it is, I want all the "more" things on the page to be expanded when the page loads, rather than making a person click more to see what's below the fold on all these.
This is the JS I need to override, I can't change it since it's loaded by the app automatically. There can be more than one of the lists hidden, I'm not sure how much harder that makes things.
function MoreFacets($more_facets_div) {
this.$more_facets_div = $more_facets_div;
this.bind_events();
};
MoreFacets.prototype.bind_events = function() {
var self = this;
self.$more_facets_div.find('.more').on('click', function (e) {
$(this).siblings('.below-the-fold').show();
$(this).hide();
});
self.$more_facets_div.find('.less').on('click', function (e) {
$(this).parent().hide();
$(this).parent().parent().find('.more').show();
});
};
$(function() {
$('.more-facets').each(function() {
new MoreFacets($(this));
});
});
It's loaded on the page and the HTML looks like this:
<h3>Additional filters: </h3>
<dl id="facets">
<dt>Collecting Area</dt>
<dd> Here's Something in the list</dd>
<dd> Here's the last in the list</dd>
<div class="more-facets">
<span class="more btn">∨ more</span>
<div class="below-the-fold">
<dd>Something That's hidden is here</dd>
<dd>Something more in this hidden list</dd>
So when the ∨ more is clicked is when the others below-the-fold appear, and that's what I want to load when the page loads. There's usually a few different lists like this on the page.
So I'm thinking what I need to do is something like run the ('.below-the-fold').show() for all the lists when the page loads?
Update A note to clarify: when the page loads now they're all hidden. I'd like them to all show when the page is loaded so no one has to click anything to have everything showing.
Another note based on another question below... It's loaded in a separate file, and I can load my file before that one. I do know that I can override other JS on the page, so I assume I can override this as well.
Based on your last edit, it sounds like you're already onto the fastest solution to your problem.
Please note, this will only work if the script is not loaded asynchronously, but if you have control of the order the scripts are loaded in, you can insert your script between the problem script and jQuery.
Your script can be something as easy as redefining the function it's using to something like this:
MoreFacets.prototype.bind_events = function() {
var self = this;
//Autostart in our open state without completely disabling the functionality
self.$more_facets_div.find('.below-the-fold').show();
self.$more_facets_div.find('.more').hide();
self.$more_facets_div.find('.more').on('click', function (e) {
$(this).siblings('.below-the-fold').show();
$(this).hide();
});
self.$more_facets_div.find('.less').on('click', function (e) {
$(this).parent().hide();
$(this).parent().parent().find('.more').show();
});
};
Now, that won't work if you don't have control over the script loading, but you might have hope even in that case, because document ready functions in jQuery are invoked in the order they're registered, so if you can't really control where your script is you might play with an alternative
$(function() {
$('.more-facets').each(function() {
$(this).find('.below-the-fold').show();
$(this).find('.more').hide();
});
});
The first will be cleaner, but the second is a fallback for more restrictive situations, and both should achieve your desired effect without completely removing the functionality, just changing the default state on load.
I am working on a jQuery project which a part of page is loaded by choosing different options usign load() method.
I have this line in my application:
$('.pe').myFunction();
This code must be executed without any event. So I can not use any code like this:
$(document).on('click','.pe',function(){...});
It works well on all preloaded elements with pe class.But it does not work on new loaded contents which have same class.
Can you help me please?
The arguably correct way of doing it is using $(document).on('.pe','click',function(){...});; however, I did program a fair amount before I discovered that. So, I know there are a couple of work around. I'd use a class to mark an item as 'completed' after adding a click event.
If you have any 'hook' to know when the new html is added you can simply call a function that instead of using an interval.
Note regarding the question: you did say no events and this uses no events.
//Simulating ajax loading
setInterval(function () {
$(document.body).append('<button class="clickable">So clickable!</button><br />');
},1000);
//Your code
setInterval(function () {
$(".clickable:not(.completed)").click(function () {
console.log('works!');
}).addClass("completed");
},10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button class="clickable">So clickable!</button>
</div>
Finally I found the answer. I just put the same code inside the loaded page.
// New page which will be loaded with its all contents ...
<script>$('.pe').myFunction();</script>
I have a simple jquery script that changes the url path of the images. The only problem is the doesn't apply after I click the load more button. So I'm trying to do a workaround where it calls the script again after clicking the button.
<script type='text/javascript'>
$(document).ready(function ReplaceImage() {
$(".galleryItem img").each(function() {
$(this).attr("src", function(a, b) {
return b.replace("s72-c", "s300")
})
})
});
</script>
HTML
Load More
While Keith's answer will get you what you are looking for, I really can't recommend that approach. You are much better off with something like this.
<script type="text/javascript">
$(function() {
var replaceImage = function() {
$('.galleryItem img').each(function() {
$(this).attr('src', function(index, value) {
return value.replace('s72-c', 's300');
});
});
};
replaceImage();
$('.js-replace-image').on('click', replaceImage);
});
</script>
Using this html
<button class="js-replace-image">Load More</button>
By taking this approach, you do not expose any global variables onto the window object, which can be a point of issue if you work with other libraries (or developers) that don't manage their globals well.
Also, by moving to a class name and binding an event handler to the DOM node via JavaScript, you future proof yourself much more. Also allows yourself to easily add this functionality to more buttons very easily but just adding a class to it.
I updated the anchor tag to a button because of the semantics of what you need to do - it doesn't link out anywhere, it's just dynamic functionality on the page. This is what buttons are best served for.
I'd also recommend putting this in the footer of your site, because then, depending on your situation, you will already have the images updated properly without having to click the button. The only need for the button would be if you are dynamically inserting more images on the page after load, or if this script was in the head of your document (meaning jQuery couldn't know about the images yet).
I hope this helps, reach out if you have questions.
What is the best unobtrusive way of invoking something after the page is being loaded in plain JavaScript? Of course in jQuery I would use:
$(document).ready(function(){...});
but I am not sure about the most reliable approach in plain js.
Clearly
window.onload = ...
is not proper solution, because it would overwrite previous declaration.
What I am trying to do is to insert an iframe into a div after the page is loaded, but maybe there are actually better ways of doing it. My plan is to do something like:
window.onload = function(divId){
var div = document.getElementById(divId);
div.innerHTML = "<iframe src='someUrl' .. >";
}
EDIT:
Apologies for not including all necessary details.
The script is not for my website - the idea is to show a part of my site (a form) on external web sites. The priority is to minimize the effort someone has to put to use my code. That is why I would like to keep everything in js file and absolutely nothing in <script> - except of <script src="http://my.website/code.js" />. If I change URL of an iframe or I would like to add some features, I would like to update the code on all other web sites without asking them to make any changes.
My approach might be wrong - any suggestions are very welcome.
//For modern browsers:
document.addEventListener( "DOMContentLoaded", someFunction, false );
//For IE:
document.attachEvent( "onreadystatechange", someFunction);
`attachEvent` and `addEventListener` allow you to register more than one event listener for a particular target.
See:
https://developer.mozilla.org/en/DOM/element.addEventListener
Also definitly worth looking at how jQuery does it:
http://code.jquery.com/jquery-1.7.js Search for bindReady.
Use window.addEventListener and the events load or DOMContentLoaded:
window.addEventListener('DOMContentLoaded',function(){alert("first handler");});
window.addEventListener('DOMContentLoaded',function(){alert("second handler");});
object.addEventListener('event',callback) will insert an event listener into a queue for that specific object event. See https://developer.mozilla.org/en/DOM/element.addEventListener for further information.
For IE5-8 use window.attachEvent('event',callback), see http://msdn.microsoft.com/en-us/library/ms536343%28VS.85%29.aspx. You can build yourself a little helper function:
function addEventHandler(object,szEvent,cbCallback){
if(typeof(szEvent) !== 'string' || typeof(cbCallback) !== 'function')
return false;
if(!!object.addEventListener){ // for IE9+
return object.addEventListener(szEvent,cbCallback);
}
if(!!object.attachEvent){ // for IE <=8
return object.attachEvent(szEvent,cbCallback);
}
return false;
}
addEventHandler(window,'load',function(){alert("first handler");});
addEventHandler(window,'load',function(){alert("second handler");});
Note that DOMContentLoaded isn't defined in IE lesser 9. If you don't know your recipient's browser use the event load.
Just put your script include at the very end of the document, immediately before or after the ending </body> tag, e.g.:
(content)
(content)
<script src="http://my.website/code.js"></script>
</body>
</html>
All of the markup above the script will be accessible via the usual DOM methods (reference). Obviously, not all ancillary resources (images and such) will be fully loaded yet, but presumably that's why you want to avoid the window load event (it happens so late).
The only real purpose of ready-style events is if you don't control where the script gets included (e.g., libraries) or you need to have something execute prior to the page load and something else after the page load, and you want to avoid having two HTTP requests (e.g., for two different scripts, one before load and one after).