Dynamic reload of src - javascript

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

Related

Why isn't the class added/removed? - Javascript [duplicate]

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();
});

Adding event listeners with Javascript DOM

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 :)

The onload() function refuses to run?

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);
}

Function called in window.onload does not recognize element

I am a bit confused here. I thought that the function specified in window.onload did not execute before the page was loaded. Nervertheless, I get an error in the below code (heres the jsfiddle version):
<script>
function updateImage(url){
document.getElementById("foo").src = url;
}
window.onload = updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux");
</script>
<img id="foo" alt="" src="http://dummyimage.com/100x100/000/fff.png&text=bar" />
It gives me:
Error: document.getElementById("foo") is null
When moving the image above the script all works well.
window.onload expects to be a function - which it will call when the page is loaded. But what you've assigned to it is not a function. You assigned
updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux");
which immediately executes the updateImage function, and since you don't have a return statement in the body of updateImage, the return value is undefined. Therefore, at the end, window.onload has the value undefined.
A solution would be to change that bit of code to:
window.onload = function(){
updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux");
}
This will cause it to call the function when the window has been loaded and do what you'd expect.
You can use trigger that will check is element loaded.
<script>
function updateImage(url){
document.getElementById("foo").src = url;
}
function initOnLoad(sElementName) {
var oElement = (sElementName == "body") ? document[sElementName] : document.getElementById(sElementName);
if(oElement != null && typeof(oElement) != "undefined") {
updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux");
}
else {
setTimeout(function() {
initOnLoad(sElementName);
}, 0);
}
}
initOnLoad('body');
</script>
<img id="foo" alt="" src="http://dummyimage.com/100x100/000/fff.png&text=bar" />
You have an error in your code.
window.onload = updateImage("...");
You are not assigning a function handler to the window onload. You are assigning the RESULT of the updateImage function. Which is executed immediately before image is loaded or even added to the DOM. To assign function handler you need:
window.onload = updateImage;
or
window.onload = function(){
updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux");
}
or by using jQuery
$(document).ready(function(){
updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux");
});

How to check image is loaded completely or not using JavaScript in Facebook

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>

Categories