Unable to change the src of an img element using javascript - javascript

I am trying to write a piece of code which replaces an image with another image on page load. But unfortunately it does not happen so. The second image does not load. i only see an icon with a cross mark after pageload. Please have a look at the below code and let me know what's wrong. Thanks in advance.
<html>
<head>
<script type="text/javascript">
function loadImage()
{
document.getElementById('ab').src ="C:\Users\Gagan\Desktop\green.png";
}
</script>
</head>
<body>
<img Id= "ab" src="C:\Users\Gagan\Desktop\red.jpg" onload="loadImage()">
</body>
</html>

In JavaScript, backslash is the escape character. If you want to include it in a string, you have to escape it using itself:
document.getElementById('ab').src = "C:\\Users\\Gagan\\Desktop\\green.png";

For future viewers of this question, I would recommend the unobtrusive JavaScript pattern for this, where the onload is done completely in JavaScript:
<html>
<head>
<script type="text/javascript">
var img = document.getElementById('ab');
function loadImage()
{
img.src ="C:\\Users\\Gagan\\Desktop\\green.png";
}
img.onload = loadImage;
</script>
</head>
<body>
<img id="ab" src="C:\Users\Gagan\Desktop\red.jpg" alt="" />
</body>
</html>

Related

JavaScript Replace function giving out errors

I want this code to replace all ':)'s with my smiley emoji. Although when I run the code I get Uncaught TypeError: Cannot read property 'replace' of undefined at ?v=0.02:10 any help would be greatly appreciated!
Code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>SVG Emoji</title>
</head>
<body>
<script>
var html = document.getElementsByTagName("html").innerHTML;
html.replace(":)", "<img src='https://csf30816.github.io/svg-emoji/emojis/smile.svg'>");
document.getElementsByTagName("html").innerHTML = html;
</script>
<h1>:) Test</h1>
</body>
</html>
Replace
document.getElementsByTagName("html").innerHTML
with
document.getElementsByTagName("html")[0].innerHTML
as getElementsByTagName returns an array.
Also, the string.replace() method returns a new string without mutating / modifying the given one. You would need to re-assign the returned string to html = html.replace(...).
Also, you need to move your <script> to the bottom. Otherwise it can't access DOM elements that appear beneath it in your HTML document, such as the <h1> element:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>SVG Emoji</title>
</head>
<body>
<h1>:) Test</h1>
<script>
var html = document.getElementsByTagName("html")[0].innerHTML;
html = html.replace(":)", "<img src='https://csf30816.github.io/svg-emoji/emojis/smile.svg'>");
document.getElementsByTagName("html")[0].innerHTML = html;
</script>
</body>
</html>
See also How to get the <html> tag HTML with JavaScript / jQuery?
For a more robust approach to replacing text within the DOM see jQuery replace all occurrences of a string in an html page
Your code and the problem you are trying to solve are doing different things. This will give you the solution you are seeking, i.e. replace all ':)'s with my smiley emoji
function replaceTextByImage(pattern, src) {
document.body.innerHTML = document.body.innerHTML.replace(
new RegExp(pattern, 'g'),
'<span style="background-size: 100% 100%; background-image: url(\'' + src + '\');">&nbsp&nbsp&nbsp&nbsp</span>'
);
}
replaceTextByImage(':\\)', 'https://csf30816.github.io/svg-emoji/emojis/smile.svg');
replaceTextByImage(':P', 'https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/svg/1f61b.svg');
replaceTextByImage(':D', 'https://what.thedailywtf.com/plugins/nodebb-plugin-emoji-one/static/images/1f603.svg');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<p>
Hello World! How are you? :). Do you like this emoji :)
</p>
<div style="font-size:50px;">How about now :)</div>
<div style="font-size:25px">You can also do this :P and this :D now!</div>
</body>
</html>
PROS
Emoji will resize according to font used.
Replaces all occurrences of a pattern
CONS
If you have an inline script in the body of your html, it may be re-executed every time the function replaceTextByImage is called because it is setting the body's innerHTML.
If you want to use jquery then don't read this answer.
But for those who can allow their script not be jquery,
Here is your code.
document.getElementsByTagName("H1")[0].innerHTML = '<img src="https://csf30816.github.io/svg-emoji/emojis/smile.svg">';
<h1>:) Test</h1>
What the problem is:
You are returning an array.
Use one element with [0]:
document.getElementsByTagName("html")[0].innerHTML = html;

Convert Raphael canvas inside div to PNG

I've created an SVG using Raphael that I want to capture and convert to PNG and then display in the open window. I have looked at some other stack overflow answers like this one. I implemented ollieg's answer to that question. Here's an example of what I'm doing:
<html>
<head>
<script src="NBA_test/lib/raphael-min.js"></script>
</head>
<body>
<div id="canvas"></div><br>
<script language="JavaScript">
var test=Raphael("canvas",50,50);
var rect=test.rect(0,0,50,50);
rect.attr({fill: '#fff000'})
window.onload = function() {
var canvas = document.getElementById("canvas");
window.location = canvas.toDataURL("image/png");
}
</script>
</body>
</html>
This should draw a yellow rectangle and output it as a png. The console confirms that the SVG is being captured correctly in the canvas var. However, the toDataURL line throws an error: "TypeError: 'null' is not an object (evaluating 'canvas.toDataURL')" I know my example is a little different in the sense that I don't have an actual canvas tag in my html, just the div that is going to get the canvas. Given that the canvas is being captured correctly, however, I don't understand why the second line throws that error.
Using canvg per the suggestion above and raphael.export.js, I have solved my problem (kind of). My minimal example now works as below:
<html>
<head>
<script src="lib/raphael-min.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/StackBlur.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
<script src="lib/raphael.export.js"></script>
</head>
<body>
<div id="raph_canvas"></div><br>
<canvas id="html_canvas" width="50px" height="50px"></canvas>
<script language="JavaScript">
var test=Raphael("raph_canvas",50,50);
var rect=test.rect(0,0,50,50);
rect.attr({fill: '#fff000', 'fill-opacity':1, 'stroke-width':1})
window.onload = function() {
var canvas_svg = test.toSVG();
canvg('html_canvas',canvas_svg);
var canvas_html = document.getElementById("html_canvas");
window.location = canvas_html.toDataURL("image/png");
}
</script>
</body>
</html>
The problem now is that my actual app, which is a little more complex, doesn't work, but I will maybe post a separate question about that.

jquery mouseover not working. working in jfiddle only

It's just a couple of lines of code: http://jsfiddle.net/z7bHt/
HTML:
<body>
<img src="http://pjg.mobi/mh/images/layover_brownstring.png" id="bowleft" width="200" height="77" alt=""/>
</body>
JAVASCRIPT:
$("#bowleft").mouseenter(function(){
console.log("worked!!!");alert("worked!!!");
});
but this simple mouseover isn't working, locally or remotely, in either chrome or firefox!
Could someone try this themselves to see if i'm going crazy or if it is my operating system? https://www.dropbox.com/s/ahpaluj2e7ru9xn/mouseover.zip
The .mouseenter code is running before the #bowleft element exists. You need to ensure that it runs after that element exists in the DOM. There are many ways to do this. I would suggest moving your JavaScript to right before </body>. You can also wrap it in:
$(function () {
Or $(document).ready(function () {, which is functionally the same.
I would also suggest using .on instead of the specific function named after the event, but this doesn't affect you here. All together:
<body>
<img src="http://pjg.mobi/mh/images/layover_brownstring.png" id="bowleft" width="200" height="77" alt=""/>
<script src="js/jquery-1.10.2.min.js"></script>
<script>
$("#bowleft").on("mouseenter", function () {
console.log("worked!!!");
});
</script>
</body>
You are trying to reference the image with your JS before it exists in the DOM.
The best thing to do is to move your JS to just before the closing body tag, like so:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<img src="http://pjg.mobi/mh/images/layover_brownstring.png" id="bowleft" width="200" height="77" alt=""/>
<script src="js/jquery-1.10.2.min.js"></script>
<script>
$("#bowleft").mouseenter(function(){
console.log("worked!!!");
alert("worked!!!");
});
</script>
</body>
</html>
If you want to keep it in the head of the document, you'll have to wrap it in a $(document).ready() callback.
try this it worked ........
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#bowleft").mouseenter(function () {
console.log("worked!!!"); alert("worked!!!");
});
});

Javascript: Does not change the div innerHTML

I really cannot understand why this does not work. I've tried couple of tricks but I just don't get it.
<html>
<head>
<script type="text/javascript">
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
</script>
</head>
<body>
<div id="results">
hey there
</div>
</body>
</html>
This is working as you can see here:
http://jsfiddle.net/gHbss/
It's important that you put the JavaScript after your HTML div container.
The problem that you're facing is that the browser runs the JavaScript as it's encountered when rendering/processing the page. At this point it will alert() your message, but the relevant element, the #results div isn't present in the DOM, so nothing can be changed.
To address this, you can either place the script at the end of the page, just before the closing </body> tag, or run the code in the onload event of the body or window.
The script has to be placed after the div#results or executed onload, otherwise the element is still unknown when you try to access it.
You need to call this script in onload event
i.e
window.onload=function(){
//your code
}
<html>
<head>
<script type="text/javascript">
function onloadCall()
{
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
}
</script>
</head>
<body onload="onloadCall()">
<div id="results">
hey there
</div>
</body>
</html>
Hope the above snippet shows you the fix

javascript tag trigger - code position on page

i use that tag to alert me when a tag has been shows up
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
strange , since this code working :
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
why the Js need to under the tag to work?
what's the problem here?
Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:
window.onload = function() {
//your code
}
Then it doesn't matter where the code is placed.
Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like
alert(document.getElementsByTagName('iframe'));
Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.

Categories