Hello I am sorry to bother you with such a simple question but this bit of code, I literally could not find anything wrong with it, but none of the alerts even trigger so I know that init isn't even been passed to window.onload. Here is the code:
window.onload()=init;
alert("The file has been linked to.");
function init(){
alert("Init has been loaded");
var button = document.getElementById("myButton");
button.onclick = handleButtonClick;
}
function handleButtonClick()
{
alert("button has been clicked");
var target = document.getElementById("target");
var image = document.createElement("<img />");
image.innerHTML = "<img src=../Images/banner_test.jpg alt=Banner height=42 width=42 />" ;
target.appendChild(image);
}
The JS is in a external js file I've linked to with:
<script type="text/javascript" src="../JS/Experiment.js" > </script>
Have I misspelt something or forgotten a parameter because as I've said none of the alarms will activate, no use talking about creating a new <img /> and adding it.
The HTML isn't a problem I've tried a simple alert() with inline <script> and it works but I need this to be in a external file.
window.onload is not a method, drop the parens ()
window.onload isn't a function and so the first line will prevent the rest from running:
window.onload()=init
It should be
window.onload=init;
alert("The file has been linked to.");
function init(){
alert("Init has been loaded");
var button = document.getElementById("myButton");
button.onclick = handleButtonClick;
}
function handleButtonClick()
{
alert("button has been clicked");
var target = document.getElementById("target");
var image = document.createElement("<img />");
image.innerHTML = "<img src=../Images/banner_test.jpg alt=Banner height=42 width=42 />" ;
target.appendChild(image);
}
note that also the init function is only available because JavaScript hoists non "var"ed functions to the top of the scope so watch out for this when you're pointing to functions like this.
As others have stated, the parens have to be dropped. Before your code runs fine, you have to fix more code, though.
document.createElement accepts a plain string as a parameter, which will be the tag name. Your current code will throw an error at that point.
When an image element has been created, the innerHTML property makes no sense for it. You have to explicitly attach attributes/properties to it (see below).
Fixed code:
function handleButtonClick()
{
alert("button has been clicked");
var target = document.getElementById("target");
//var image = document.createElement("<img />"); // INVALID!!
var image = new Image(); // or: document.createElement("img");
//image.innerHTML = "<img src=../Images/banner_test.jpg alt=Banner height=42 width=42 />" ;
image.src = "../Images/banner_test.jpg";
image.alt = "Banner";
image.height = 42;
image.width = 42;
target.appendChild(image);
}
Related
This question already has answers here:
javascript onclick happening on page load
(5 answers)
Closed 5 months ago.
I am trying to create a link, which looks and feels like an <a> tag item, but runs a function instead of using the href.
When I try to apply the onclick function to the link it immediately calls the function regardless of the fact that the link was never clicked. Any attempt to click the link thereafter fails.
What am I doing wrong?
HTML
<div id="parent">
Send
</div>
Javascript
startFunction();
function secondFunction(){
window.alert("Already called!?");
}
function startFunction() {
var sentNode = document.createElement('a');
sentNode.setAttribute('href', "#");
sentNode.setAttribute('onclick', secondFunction());
//sentNode.onclick = secondFunction();
sentNode.innerHTML = "Sent Items";
//Add new element to parent
var parentNode = document.getElementById('parent');
var childNode = document.getElementById('sendNode');
parentNode.insertBefore(sentNode, childNode);
}
JsFiddle
As you can see I tried two different ways of adding this onclick function, both of which have the same effect.
You want .onclick = secondFunction
NOT .onclick = secondFunction()
The latter calls (executes) secondFunction whereas the former passes a reference to the secondFunction to be called upon the onclick event
function start() {
var a = document.createElement("a");
a.setAttribute("href", "#");
a.onclick = secondFunction;
a.appendChild(document.createTextNode("click me"));
document.body.appendChild(a);
}
function secondFunction() {
window.alert("hello!");
}
start();
You could also use elem#addEventListener
a.addEventListener("click", secondFunction);
// OR
a.addEventListener("click", function(event) {
secondFunction();
event.preventDefault();
});
I am trying to setting of src dynamically in my code, But it does n't work.
I dont know where I am missing. Please find the fiddle link below
function test() {
alert("Inside function");
var img = document.getElementById('test');
img.src = "https://s3.amazonaws.com/prod-appreiz/team/5.png";
}
Fiddle
Make sure the function is within scope, which means setting up the fiddle correctly with "no wrap-in body".
Also, use a different function name as window.test is already defined, it's the element you're trying to get because ID's are written to the window, and using the same name for the function overwrites the reference to the ID test
function _test(){
alert("Inside function");
var img = document.getElementById('test');
img.src = "https://s3.amazonaws.com/prod-appreiz/team/5.png";
}
FIDDLE
Try this:
$(document).delegate(':file', 'change', function() {
alert("Inside function");
var img = document.getElementById('test');
img.src = "https://s3.amazonaws.com/prod-appreiz/team/5.png";
});
Fiddle
I have a few javascript routines that I need to run with my application. When I run the application and go to view source, I see the javascript file import, and when I click on it, I am taken to the javascript file, so I know it is being brought down to the client. Right now, I have a simple alert in the beginning of the method I am calling, but that isn't even happening, so I'm not sure what's going on.
Does this look like the correct way to call the javascript when the button is clicked?
<p><input type="button" value="Add File" onclick="go();" /></p>
Here is the javascript file:
var typeAId= 0;
var typeBId= 0;
function addNewDocument(parentId, elementTag, elementId, html) {
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function go(){
alert('ok');
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
function addNewDocument(input) {
var fileToRemove = 'file-';
alert('ok');
var elementName = null;
if(input === 'formAInput'){
elementName = 'formA[]';
typeAId++;
fileToRemove = fileToRemove+typeAId;
} else {
elementName = 'formB[]';
typeBId++;
fileToRemove = fileToRemove+typeBId;
}
var html = '<input type="file" name="'+elementName+'" /> ' +
'Remove';
if(input === 'formAInput'){}
addElement('typeAFilesDiv', 'p', 'file-' + typeAId, html);
} else {
addElement('typeBFilesDiv', 'p', 'file-' + typeBId, html);
}
alert('end');
}
Here is how I am importing the javascript:
<script src="/js/myJS.js"></script>
The js directory is located under the 'war' directory in my Google App Engine Project.
When I click the button, I do not see an alert.
Additional documentation, code, and screenshots would help the community answer more holistically. However, to answer your most basic question, yes, that is the correct way to use the onclick attribute.
I hypothesize that the JavaScript addFile function is not doing what you want it to or something is wrong with the document.ready event.
I'm having trouble adding eventListener to through javascript. Ok, I have a function that creates 4 anchor elements. I want to add an event to them onmouseover that calls a function to change their backkground color. Here's the code (look at the next to last line of createAnchor() to find the relevant code line.
function createAanchor(index) {
var a = document.createElement("a");
var text = getText(index);
var a = document.createElement("a");
var t = document.createTextNode(text);
a.href = getHref(index);
a.appendChild(t);
a.style.textAlign = "center";
a.style.fontSize = "1.2em";
a.style.color = "white";
a.style.fontFamily = "arial";
a.style.fontWeight = "bold";
a.style.textDecoration = "none";
a.style.lineHeight = "238px";
a.style.width = "238px";
a.style.margin = "5px";
a.style.background = eightColors(index);
a.style.position = "absolute";
a.addEventListener("onmouseover", changeColor());
return a;
}
function changeColor() {
alert("EVENT WORKING");
}
Ok here's the problem. When the function gets to a.addEventListener("onmouseover", changeColor()); the function changeColors() executes, but it does not execute later on onmouseover Why is this?
There is no such event onmouseover, the event is called mouseover.
You have to pass a function reference to addEventlistener. () calls the function, as you already noticed, so... don't call it.
This is how it should be:
a.addEventListener("mouseover", changeColor);
I recommend to read the excellent articles about event handling on quirksmode.org.
It's because you wrote changeColors() instead of just changeColors. The () tell JavaScript to call the function.
In other words, changeColors by itself is a reference to the function, while changeColors() refers to the function and then calls it. The result of the function call (the return value from the function) is what's ultimately passed to addEventListener().
Ok I think we need to understand when to use the prefix "on" with the event type. In IE 8 or less then IE8 we use attachEvent and detachEvent which are equivalent to addEventListener and removeEventListener. There are some differences which are not required for this question.
While using attachEvent the event type is prefixed with "on" but in addEventListener no prefix is used.
hence,
elem.attachEvent("onclick",listener); // <= IE8
elem.addEventListener("click",listener,[,useCapture]); // other browsers
I've needed to do something like that too. I have an infoWindow in my map and I need to handle a click event on paragraph in that infoWindow. So I did it like this:
google.maps.event.addListener(infoWindow, 'domready', function()
{
paragraph = document.getElementById("idOfThatParagraph");
paragraph.addEventListener("click", function()
{
//actions that I need to do
});
});
It works for me. So I hope it will help someone :)
I m trying to execute some code when image is not loaded. I m using following code:
<script language="javascript">
object = new Image();
object.src = '$imageurl';
if(!object.complete)
{
//do something
}
</script>
But this is not working in Facebook. Please help me.
Use the onload event which fires when image has been loaded like this:
object.onload = function(){
// image has been loaded
};
Also have a look at:
Getting an Image's onload to Fire
Update:
To run code unless image has not been loaded, you could do this way:
<script language="javascript">
object = new Image();
// here image is not loaded yet
object.onload = function(){
// image has been loaded
};
// image loaded, show it
object.src = '$imageurl';
</script>
I suspect you are using php by seeing $imageurl, you need to replace the line:
object.src = '$imageurl';
With:
object.src = '<?php echo $imageurl;?>';
Run a function using window.setInterval while the image is loading and stop it as soon as it has loaded.
function () {
var img = new Image();
var intervalId = window.setInterval(function () {
/* stuff to do with "img" while it is loading */
}, 250);
img.onload = function () { window.clearInterval(intervalId); }
img.src = 'http://example.com/image.jpg';
}
You can use the onLoad event
<script language="javascript">
object = new Image();
object.src = '$imageurl';
object.onLoad = imageHasLoaded();
</script>