Window.onload and ordering - javascript

In the code below, I can't seem to understand the ordering of events. When I load this in the browser, I get the alert before the first div renders and the .onclick event listener cannot find the translate_button element to attach to. I thought because of the use of window.onload, my script would execute after the above html loaded. Does this have to do with the inline javascript within the html?
<div id='MicrosoftTranslatorWidget' class='Dark' id='translate_button'></div><script type='text/javascript'>setTimeout(function(){{var s=document.createElement('script');s.type='text/javascript';s.charset='UTF-8';s.src=((location && location.href && location.href.indexOf('https') == 0)?'https://ssl.microsofttranslator.com':'http://www.microsofttranslator.com')+'/ajax/v3/WidgetV3.ashx?siteData=ueOIGRSKkd965FeEGM5JtQ**&ctf=True&ui=true&settings=Manual&languages=es,pt,fr,it,tr,zh-CHS,zh-CHT,ru,de,en';var p=document.getElementsByTagName('head')[0]||document.documentElement;p.insertBefore(s,p.firstChild); }},0);</script>
<div class='disclaimer-link' id='disclaimer-link' style='display:none'>Disclaimer</div>
<script type="text/javascript">
window.onload = function () {
var button = document.getElementById("translate_button");
button.onclick = alert("lol");
};
</script>

You're assigning function execution. If you want to assign actual function you need something like
button.onclick = function() { alert("lol"); }
Another thing - you have ID defined twice for the DIV. Remove one and use the one that remains.

Related

How to add a class without access to HTML

I want to add an additional class to an input. I have no access to the HTML to change the code.
I tried the below. I don't really know JS, but have to get this done for work.
<script type="text/javascript">
function changeClass(){
document.getElementById("en__field_supporter_emailAddress").className += " xverify_email";
}
window.onload = function(){
document.getElementsByTagName("button").addEventListener( 'click', changeClass);
}
</script>
I want the JS to insert the "xverify_email" class into the email address input line (which has the id en__field_supporter_emailAddress and also already has a class that must remain there) so that it can call the subsequent xverify JS to work.
I'm assuming you have a set of buttons, so you want to bind the event click to every button in the page:
Array.from(document.querySelectorALl('button')).forEach(function(btn) {
btn.addEventListener('click', changeClass);
});
I recommend you to embrace the attribute classList:
function changeClass() {
document.getElementById("en__field_supporter_emailAddress").classList.add("xverify_email");
}

A simple Unobtrusive JavaScript example

<script>
var el = document.getElementById('btn');
e1.onclick=function()
{
//
alert('hello');
};
</script>
<button type="button" id="btn" >Log-in</button>
I am simply testing how unobstrusive javaScript works with a simple button onclick() event but when i click on the Log-in button nothing happens alert box doesn appears
Your script appears before the button.
It runs before the button is added to the DOM.
document.getElementById('btn') doesn't find the button because the button doesn't exist then.
Move the script after the button or put it in a function and call that function after the button exists (e.g. from the window's load event).
Also, don't rename your variables in the middle of your code. A lower case L and the numeral 1 aren't interchangeable.
The issue is you try to attach the handler before the element exists. <script> tags are executed immediately and so the browser hasn't created the button element at that time.
A solution would be to wrap it in window.onload:
window.onload = function(){
var el = document.getElementById('btn');
e1.onclick=function()
{
//
alert('hello');
};
};
Alternatively you can use the DOMContentLoaded event. This differs from onload because it doesn't wait for images and CSS to be loaded. It isn't supported by IE8 or lower though:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("ready to attach events");
});
yes as said by above 2 answers you can wrap your code in window.onload else you can write a function and call it onclick event of button as shown below
function myfunction() {
alert('Hello');
};
<input type="button" onclick="myfunction()" value="Click Me!" />
http://jsfiddle.net/wf8yJ/13/

document and image onclick priority

I have a document. I can't change it.
It has an image.
Image has onclick event (imageCallback).
Also I have a bookmarklet. I want to do document.onclick = documentCallback;
And I want to make documentCallback have priority: it should runs first. And imageCallback shouldn't run at all until I close the bookmarklet.
How can I do it?
Add the event handler through addEventListener and set useCapture parameter to true:
document.addEventListener('click', documentCallback, true)
Events can be dispatched in two phases, the bubbling phase and the capture phase, the capture phase comes first, you should Take a look at this
delete your imageCallback-function, and lookup the event-Source in your document.onclick:
html:
<img id="id-of-your-img" src="...">
javascript:
document.onclick = function (event) {
// do what needs to be done first
//do whatever you want to do when the img was clicked
if(event.srcElement.id === 'id-of-your-img') {
}
};
edit (i think i know now what you want to achieve (the hint "bookmarklet" was important):
var yourimg = document.getElementById('your-img-id')
, imgCallback = yourimg.onclick;
yourimg.onclick = function () {};
document.onclick = function (event) {
// do what needs to be done first
if(event.srcElement === yourimg) {
imgCallback();
}
};
what is done here? we get the image, overwrite the current click handler (but save it into our imgCallback-Var. when the document is clicked, we do whatever we want to do, and then take a look if the event-source was our image. if so, we execute our imgCallback-Function.

load() method is entered (executed) many times

in my html page, i have an image, and on clicking a button, i'm calling the function TestLoad() where it is changing the src of the image and when the image is loaded i'm doing something...
take an example:
javascript:
function TestLoad() {
alert('before');
$('#ImgTest').attr('src', 'Images/Image1.jpg');
$('#ImgTest').load(function () {
alert('after');
});
}
html:
<img id = "ImgTest" alt="" src="" style="width:100px; height:100px"/>
<input type="button" onclick ="TestLoad();" value="TestLoad"/>
my problem is:
when i click the button for the first time, i'm getting the alert "after" one time and if i click another time, the alert will be displayed two time and the third, 3 times...
Kindly advice
Thanks
Each time your handler executes, it adds another new load handler. You only need to assign the handler a single time. If you really need to do it this way, you can either remove the existing handlers first or check the events to see if it's already being handled:
var $imgTest = $('#ImgTest');
$imgTest.attr('src','Images/Image1.jpg');
$imgTest.unbind('load');
$imgTest.load(function(){
alert('after');
});
Or:
var events;
var $imgTest = $('#ImgTest');
$imgTest.attr('src', 'Images/Image1.jpg');
events = $imgTest.data('events');
if(events !== null && typeof events.load === undefined){
$imgTest.load(function(){
alert('after');
});
}
Your onclick event is probably binding another load event.
You don't need to keep adding the event to it. It already exists. If you need to bind another one, you'll want to unbind the previous event first.
.on("load", function() { ... });
.off("load");
You are binding multiple functions in your event handler
//bind this outside of your test load method
$('#ImgTest').load(function () {
alert('after');
});
function TestLoad() {
alert('before');
$('#ImgTest').attr('src', 'Images/Image1.jpg');
}

How can I call this script from a button click

I'd like the following script to execute as the result of a button click()
<script src="https://www.googleapis.com/buzz/v1/activities/search?callback=handler&alt=json&q=ruby&max-results=100"></script>
All client side code; html & javascript. I'm calling a javascript function on the button click and tried using document.write() to write out the above, but I can't get the script to execute.
Or, maybe the code is executing, but its not reaching the callback=handler.
I do almost all server side coding (asp.net) and I'm a little lost in the javascript/client side of things.
The handler should be the name of a client-side function that will receive the data. You should also add a click event handler to the button and use AJAX to retrieve the results. Here's how you would do it using jQuery (which I recommend). Note using jQuery you can pass the name of the handler as ? and it will construct a handler for you using the anonymous function you supply.
<script type="text/javascript">
$(function() { // execute on document ready
$('#ButtonID').click( function() { // add the click event handler to button
$.getJSON( 'https://www.googleapis.com/buzz/v1/activities/search?callback=?&alt=json&q=ruby&max-results=100', function(result) {
// do something with the result
});
});
});
</script>
How about this?
window.onload = function() {
var btn = document.getElementById('id_of_your_button');
btn.onclick = function() {
var scr = document.createElement('script');
scr.src = "https://www.googleapis.com/buzz/v1/activities/search?callback=handler&alt=json&q=ruby&max-results=100";
document.getElementsByTagName('head')[0].appendChild(scr);
};
};

Categories

Resources