javascript-- changing the innerHTML of an image - javascript

So I JUST asked a question and I've already hit another roadblock. Thanks so much to the stackoverflow community for helping me out so much recently :)
Every time I see people changing the innerHTML of some tag, they use document.getElementByID(id).innerHTML. My images do NOT have ids, nor do I want to give each and every one of them an id.
Here is my code:
function clickImages()
{
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++)
{
var delegate = function() { hover(this); };
images[i].onmouseover = delegate;
}
}
function hover(img)
{
img.innerHTML = "Text!";
}
The innerHTML doesn't seem like it's working; when I mouse over the image nothing changes.
Thanks in advance! Let me know if I can clarify!

An image is itself a replaced element, so there is no innerHTML to replace.
Based on your comment, if you want to add HTML adjacent to the image, you could do this:
img.insertAdjacentHTML('afterend', 'HTML code');
You could also change 'afterend' to 'beforebegin' if you wanted to add the HTML before the image.
Writing on the image itself would be much more complicated and would require positioning another element above it with a transparent background, or using the image itself as the background of another element, or a variety of other similar techniques.

Element.innerHTML
innerHTML sets or gets the HTML syntax describing the element's
descendants
innerHTML means the HTML that comes between the start and end HTML tags. Images don't have innerHTML
I am not sure what you want to achieve.
If you want to have a text displayed onmouseover, you can use the title attribute to do that.. for example:
<img src="smiley.gif" alt="Smiley face" title="Hello" />
If you are trying to replace the image with text on onmouseover ... then as an example (only to show the possibilities), the following code will hide the image & display a text onmouseover and make the image visible & remove the text onmouseout (although not very satisfactorily IMHO, more work has to be done on the code to improve it)
Please note: There shouldn't be any gap between the image tag and the span for this particular code to work. Also, a negative margin-left added to the span element can make it appear over the location of the image.
<img onmouseover="toText(this)" onmouseout="toImage(this)" src="smiley.gif" alt="Smiley" /><span style="visibility: hidden; margin-left: -30px;">Show Text</span>
function toText(img) {
img.style.visibility = 'hidden';
img.nextSibling.style.visibility = 'visible';
}
function toImage(img) {
img.style.visibility = 'visible';
img.nextSibling.style.visibility = 'hidden';
}
Good luck
:)

Related

What Javascript if/else statement can return an enlarged image to its default size?

I am new to this website and to coding in general. I am having trouble attempting to get an image to shrink back to its "small" size after being enlarged by a single click.
This is my HTML element:
<img src="http://image.com/123.jpg"
id="smart_thumbnail"
class="small"
This id and class cannot be changed, as it is for an assignment. The "small" class automatically turns the image into a thumbnail. It enlarges upon clicking, but I cannot get it to return to its "small" state by clicking it again. It must be done with an if/else statement.
Here is the Javascript template given:
document.addEventListener("DOMContentLoaded", function(event) {
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
thumbnailElement.className = "";
});
});
The double quotes is the "enlarge" class.
Thank you, and I apologize if this post does not fit the format required on this site. I also searched everywhere for this solution but could not find it for the life of me.
This can be done using the DOM classList attribute:
thumbnailElement.classList.toggle("small");
This will remove the small class from the element if it is present, otherwise it will add it.

Using Javascript to show/hide elements depending on content in div

I am relatively inexperienced with JavaScript, and I'm working on a project that's turned into a real trial by fire for me, but hopefully this is a question that has a stupidly straightforward answer.
I'm trying to write a script that will show/hide different links on a page by changing the display style of different links.
I want to use a div element and have different links available if the user drags different images into the div. The links are in clickable pictures.
Example-
I want this linked element 'link' to be displayed only if "First_Image.png" has been dragged and dropped into div2:
<a id='link' href='link.html' style='display: none;'><IMG src="../Image.png"></a>
My div id is "div2", and it starts out empty as such:
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
Images on the page are set up as:
<IMG src="First_Image.png" id="First_Image" draggable="true"
ondragstart="drag(event)">
There are several such droppable images on the page. My attempt at this script is:
<script>
if (document.getElementById("div2").getElementsByTagName('img') == "First_Image")
document.getElementById('link').style.display = 'block';
return (false);
</script>
I'm not sure if my problem is that I'm not getting the information I think I am from the image in the div, or if my simple if statement isn't doing what I think it's doing. :/
If you're trying to get the values from the attributes (as the src is an attribute). You can try out Element.getAttribute.
https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute
document.getElementById("div2").getElementsByTagName("img").getAttribute("src");
Step by step would be:
var id = document.getElementById("div2");
var elem = id.getElementsByTagName("img");
var atr = elem.getAttribute("src");
/* for comparing */
if(atr == "First_Image.png") {
return false;
}
This will produce this: First_Image.png. And also, write this:
return false; /* not (false) */
I think the error is in your comparison
if (document.getElementById("div2").getElementsByTagName('img').src.indexOf("First_Image") > -1)

How to style with JavaScript

I am trying to use style attribute for JavaScript. But, apparently, I was doing something wrong with it. I am new in JavaScript so a general idea about style attribute for JavaScript would be great. I want to change the place, color and text-decoration etc. of JavaScript elements. I thought that declaring style attribute for div changeMe in HTML will be applied for the JavaScript. Because, JavaScript takes id of it. I wanted to use all of the style attributes that are in the div. Where am I missing? Here is my attempt to do it:
<div id="changeMe" style="position: absolute;text-decoration: none;
color: white;right:43%; top: 90px;">
<a href="home.php" >Go to homepage</a>
</div>
Javascript:
var testElement = document.getElementById("changeMe");
var text = "aaa".document.getElementById("changeMe");
text.style.textDecoration = "none"; //I changed style here too because first did not
//work.
check.onfocus= function()
{
testElement.innerHTML = text.link("index.php");;
}
Please help me understand the structure.I am stuck.Thanks
Your JavaScript will error here:
var text = "aaa".document.getElementById("changeMe");
…since "aaa" is a string and strings do not have a document property. The rest of the script won't execute.
If you fixed that line, then:
text.style.textDecoration = "none";
… would have no effect. The text-decoration is part of the link's style, not the div's.
You need to style the <a> element. If you really want to get to it via JS then you can:
testElement.getElementsByTagName('a')[0]
But you would probably be better off just using a stylesheet:
#changeMe a { text-decoration: none; }
But make sure you do something else to make it clear that the piece of non-underlined text is a link.
You're trying to style the div but you need to apply your text-decoration and color styles to the a tag itself for it to take effect.
All of this can easily be done with cascading style sheets instead, by the way.
document.getElementById("changeMe").firstChild.style.textDecoration = "none";
Working Example: http://jsfiddle.net/8Evyq/
Something definitely fishy here.
var text = "aaa".document.getElementById("changeMe");
// Without those "aaa"
var text = document.getElementById("changeMe");
// To change the <a> style inside the 'changeMe' <div>
var alinks = text.getElementsByTagName("a");
for (var i=0; i<alinks.length; i++) {
alinks[i].style.textDecoration = "none";
}
Here it is in action.

How to change a website image with javascript?

I'm working with my first Greasemonkey script.
And its for a website that have a logo, i want to change the image to a image i have created, and i wonder how i do this?
like use JavaScript to edit the current html document and replace the image.
Thanks for any help!
Edit: The image is inside a <img> tag, the image i want to change/replace is in this code:
<img class="fb_logo img" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo" width="170" height="36">
Here is the javascript code i tryed and didnt work:
var myImage = document.querySelector('.fb_logo img');
myImage.src = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
var logos = document.getElementsByClassName("fb_logo");
for( var i = 0; i < logos.length; i++ )
{
// true for all img tags with the fb_logo class name
if( logos[ i ].tagName == "IMG" )
{
logos[ i ].src = "http://www.computerweekly.com/blogs/it-downtime-blog/lolcat-tan.jpg"
}
}
Knowing that you can use browser-specific javascript is a plus.
Use querySelectorAll.
var img = document.querySelectorAll('.yourClass')[0];
Note: you're possibly selecting more than one element, so it's returning a nodelist rather than a single node, remember to select the first item in the list.
Better yet, use querySelector
var img = document.querySelector('.yourClass');
Okay, here's a complete Greasemonkey script that swaps the logo image at Facebook under real-world conditions (meaning that the image may be in different places and you have to deal with the container and background images, etc.).
Note that this script looks for the image in two types of locations, and deals with the surrounding HTML, and CSS, if necessary.
Also note that it uses jQuery -- which is a godsend for writing GM scripts.
Finally: note that I avoid Facebook, and only know of the one logo location (plus the one that the OP reports. If there are new/different locations, deal with them in a similar manner.
// ==UserScript==
// #name _Facebook Logo Swap
// #include http://www.facebook.com/*
// #include https://www.facebook.com/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
/*--- Found FB logo at:
"h1#pageLogo a" as a backgound image.
It's reportedly also at: "img.fb_logo.img"
*/
var desiredImage = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
//--- Straight image swap:
$('img.fb_logo').attr ('src', desiredImage);
/*--- Replace the link's -- with the logo as a background -- contents with just a plain image.
Since this image is transparent, clear the old BG image.
Also constrain the new img to its container.
*/
$('#pageLogo a').css ('background-image', 'none')
.append ('<img>').find ('img') .attr ('src', desiredImage)
.css ( {width: '100%', height: '100%'} );
find the image tag and replace the src attribute.
var myImage = document.getElementById(idOfImageYouNeedToChange);
myImage.src = "your_image";
Pretty straightforward.
You can do this very simply with jQuery
$('.fb_logo').attr('src','newimage.jpg');
you have to get the reference to your img element first, better use id instead of a class, since getElementsByClassName is not supported in IE until ie9:
with raw javascript (there are many ways of doing this. this is just the one):
var theImg = document.getElementById('imageId');
theImg.src = 'someNewPath'
with something like jQuery(js library) - you can easily select by class or by id or by tag etc:
$('.yourPicClass').attr('src', 'someNewPath')
How about using the DOM to find that specific attribute and change it to whatever?
<html>
<body>
<img class="fb_logo img" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo">
</body>
<script type="text/javascript">
var yerImg = document.getElementsByTagName("img");
yerImg[0].setAttribute("src", "http://goo.gl/JP8bQ");
</script>
</html>
querySelector:
return the first matching Element node within the node’s subtrees. If there is no such node, the method must return null.
querySelectorAll:
return a NodeList containing all of the matching Element nodes within the node’s subtrees, in document order. If there are no such nodes, the method must return an empty NodeList.
The Use :
var element = baseElement.querySelector(selectors);
var elementList = baseElement.querySelectorAll(selectors);
Sample :
<html>
<body>
<img class="fb_logo" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo">
</body>
<script type="text/javascript">
var myImageList = document.querySelectorAll('.fb_logo');
myImageList[0].src = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
</script>
</html>

How to change a website image with javascript? [duplicate]

I'm working with my first Greasemonkey script.
And its for a website that have a logo, i want to change the image to a image i have created, and i wonder how i do this?
like use JavaScript to edit the current html document and replace the image.
Thanks for any help!
Edit: The image is inside a <img> tag, the image i want to change/replace is in this code:
<img class="fb_logo img" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo" width="170" height="36">
Here is the javascript code i tryed and didnt work:
var myImage = document.querySelector('.fb_logo img');
myImage.src = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
var logos = document.getElementsByClassName("fb_logo");
for( var i = 0; i < logos.length; i++ )
{
// true for all img tags with the fb_logo class name
if( logos[ i ].tagName == "IMG" )
{
logos[ i ].src = "http://www.computerweekly.com/blogs/it-downtime-blog/lolcat-tan.jpg"
}
}
Knowing that you can use browser-specific javascript is a plus.
Use querySelectorAll.
var img = document.querySelectorAll('.yourClass')[0];
Note: you're possibly selecting more than one element, so it's returning a nodelist rather than a single node, remember to select the first item in the list.
Better yet, use querySelector
var img = document.querySelector('.yourClass');
Okay, here's a complete Greasemonkey script that swaps the logo image at Facebook under real-world conditions (meaning that the image may be in different places and you have to deal with the container and background images, etc.).
Note that this script looks for the image in two types of locations, and deals with the surrounding HTML, and CSS, if necessary.
Also note that it uses jQuery -- which is a godsend for writing GM scripts.
Finally: note that I avoid Facebook, and only know of the one logo location (plus the one that the OP reports. If there are new/different locations, deal with them in a similar manner.
// ==UserScript==
// #name _Facebook Logo Swap
// #include http://www.facebook.com/*
// #include https://www.facebook.com/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
/*--- Found FB logo at:
"h1#pageLogo a" as a backgound image.
It's reportedly also at: "img.fb_logo.img"
*/
var desiredImage = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
//--- Straight image swap:
$('img.fb_logo').attr ('src', desiredImage);
/*--- Replace the link's -- with the logo as a background -- contents with just a plain image.
Since this image is transparent, clear the old BG image.
Also constrain the new img to its container.
*/
$('#pageLogo a').css ('background-image', 'none')
.append ('<img>').find ('img') .attr ('src', desiredImage)
.css ( {width: '100%', height: '100%'} );
find the image tag and replace the src attribute.
var myImage = document.getElementById(idOfImageYouNeedToChange);
myImage.src = "your_image";
Pretty straightforward.
You can do this very simply with jQuery
$('.fb_logo').attr('src','newimage.jpg');
you have to get the reference to your img element first, better use id instead of a class, since getElementsByClassName is not supported in IE until ie9:
with raw javascript (there are many ways of doing this. this is just the one):
var theImg = document.getElementById('imageId');
theImg.src = 'someNewPath'
with something like jQuery(js library) - you can easily select by class or by id or by tag etc:
$('.yourPicClass').attr('src', 'someNewPath')
How about using the DOM to find that specific attribute and change it to whatever?
<html>
<body>
<img class="fb_logo img" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo">
</body>
<script type="text/javascript">
var yerImg = document.getElementsByTagName("img");
yerImg[0].setAttribute("src", "http://goo.gl/JP8bQ");
</script>
</html>
querySelector:
return the first matching Element node within the node’s subtrees. If there is no such node, the method must return null.
querySelectorAll:
return a NodeList containing all of the matching Element nodes within the node’s subtrees, in document order. If there are no such nodes, the method must return an empty NodeList.
The Use :
var element = baseElement.querySelector(selectors);
var elementList = baseElement.querySelectorAll(selectors);
Sample :
<html>
<body>
<img class="fb_logo" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo">
</body>
<script type="text/javascript">
var myImageList = document.querySelectorAll('.fb_logo');
myImageList[0].src = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
</script>
</html>

Categories

Resources