JavaScript Function to change HTML not working - javascript

I have an assignment to do the following: Change the text of the div with the id = "image" to the alt text of the preview image.
I have tried this:
function upDate(previewPic){
document.getElementById("image").innerHTML=element.alt;
}
This is my HTML code for the div:
<img class = "preview" alt = "Styling with a Bandana" src = "img.jpg" onmouseover = "upDate(this)">
It is not working for me, what am I doing wrong?

this should work, you have to get the attribute value first in order to set it
function upDate(previewPic){
var x = document.getElementById("image").getAttribute('alt')
document.getElementById("image").innerHTML= x;
}

Can you try this
<img class = "preview" alt = "Styling with a Bandana" src = "img.jpg" onmouseover = "upDate(this);">
<div id="image">
</div><!-- -->
<script>
function upDate(previewPic){
document.getElementById("image").innerHTML=previewPic.alt;
}</script>

You can try this code
function upDate(previewPic){
var image = document.getElementById("YourimgId");
document.getElementById("image").innerHTML= image.getAttribute("alt");
}

I think you do not define the id of the Image tag
Ref:https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_element_innerhtml
Also, an alter message has another div tag. That is better for the clear output

Related

Using JS to change the URL of a div background image, but it links to the CSS style sheet not the image

I am trying to use JavaScript to change the background-image property of a div to a different URL, writing a function to do so and calling the function with an onHover event. However, it does not function the way I would please and checking Firefox Developer Tools shows that the URL is actually to the style sheet I am using. Any ideas as to what could be causing this?
The HTML
This is where I have called the function.
<img class = "preview" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg" alt = "Young Puppy" onmouseover = "upDate(this)" onmouseout = "unDo()">
This is the div I am trying to edit.
<div id = "image">
Hover over an image below to display here.
</div>
The Javascript
function upDate(previewPic){
document.getElementById(image).style.backgroundImage = "url('" + previewPic.src + "')";
}
I think you forgot the ' on getElementById
function upDate(previewPic){
document.getElementById('image').style.backgroundImage = "url('" + previewPic.src + "')";
}
Your typo wasn't invalid but it looked for the content of your image variable. Like:
function upDate(previewPic){
// Identical result using a variable
let image_id = 'image';
document.getElementById(image_id).style.backgroundImage = "url('" + previewPic.src + "')";
}

change src url from style tag using js

i am getting image url in style tag by default i want to replace src="#" with the image url in the style tag using js i dont know how to do this
<img src="#" style="background:url('https://example.com/1.jpg') no-repeat center center;-webkit-background-size:cover;background-size:cover;width:660px;height:330px;"class="demo-class">
final code is like
<img src="https://example.com/1.jpg" style="background:url('https://example.com/1.jpg') no-repeat center center;-webkit-background-size:cover;background-size:cover;width:660px;height:330px;"class="demo-class">
You want to parse the current style of the element, get the URL out and update the src attribute.
To remove style, use:
img.removeAttribute('style');
var img = document.querySelector('img'),
// parse image URL and strip away url('')
imgURL = img.style.backgroundImage.replace('url("','').replace('")','');
img.src = imgURL;
// remove style attribute afterwards.
img.removeAttribute('style');
<img src="#" style="background:url('https://unsplash.it/400') no-repeat center center;-webkit-background-size:cover;background-size:cover;width:660px;height:330px;"class="demo-class">
//using javascript
document.getElementById('imgTagId').src = 'https://example.com/1.jpg';
//using jquery
$('#imgTagId').attr('src','https://example.com/1.jpg');
//using style background-image
var imageUrl = $('#imgTagId').css("background-image");
document.getElementById('imgTagId').src = imageUrl.split(/"/)[1];
You can select img tags by class name like below and change src property:
var imgs = document.getElementsByClassName('demo-class')
var img = imgs[0];
img.src = img.style.backgroundImage.replace(/url\((.*)\)/,'$1');
img.style.backgroundImage = null
<img src="#" style="background:url('https://example.com/1.jpg') no-repeat center center;-webkit-background-size:cover;background-size:cover;width:660px;height:330px;" class="demo-class">
Give your image an tag an id then you can do something like this:
document.getElementById("imageid").src="../template/save.png"
for more information there is a similar question
Programmatically change the src of an img tag

Get image preview to another div on click

I have a little problem with my image preview, because I would like get photo from #ImagePreview to #photo2 on click confirm button.
https://jsfiddle.net/0xd4odyf/3/
HTML
<img id="ImagePreview">
<input type="file" class="InputFile" onchange="document.getElementById('ImagePreview').src =window.URL.createObjectURL(this.files[0])">
<div id="photo2"></div>
<button id="confirm">confirm</button>
You can get the src attribute of the image (#ImagePreview) you selected and then set it as background-image attribute of the div(#photo2).
$("#confirm").click(function()
{
var img = $('#ImagePreview').attr('src');
$("#photo2").css('background-image','url(' + img + ')');
});
Example : https://jsfiddle.net/0xd4odyf/5/
Maybe you've already solved this problem, but perhaps someone will need it. Above problem is soloved using jquery, and I show solution using pure javascript.
let confirmButton = document.getElementById('confirm');
let photo2 = document.getElementById('photo2');
confirmButton.addEventListener('click', function(e){
let srcAttr = document.getElementById('ImagePreview').getAttribute('src');
let newImg = document.createElement('img');
newImg.setAttribute('src', srcAttr);
photo2.appendChild(newImg)
})
And the fiddle: https://jsfiddle.net/1Lzpy42b/

How to add change an image's text in JS / HTML

Basically, what I'm trying to do is I am trying to change an images alt "text".
In other words: I'm trying to do something like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var num = 0;
setInterval(function(){asdfjkl.InnerHTML="Number: " + num}, 500);
setInterval(function(){num+=1;}, 100);
</script>
</head>
<body>
<image id="asdfjkl" src="asdf.png">Hello!</image>
</body>
</html>
But the script has no effect at all on the image's text. If someone could help that would be awesome, thanks!
The image tag is used inside svg elements, for HTML use img tag and they are self closing tags <img src="" />.
It's not InnerHTML, it is innerHTML and you don't even need to use it in your case.
To set the alt attribute of the img, simply use asdfjkl.alt.
var asdfjkl = document.getElementById('asdfjkl');
var num = 0;
setInterval(function() {
asdfjkl.alt = "Number: " + num
}, 500);
setInterval(function() {
num += 1;
}, 100);
<img id="asdfjkl" src="" alt="Hello!" />
You need to use img tag, instead of image. You cannot use the element id directly like this. Use getElementById("Elem ID Here"). Also innerHTML in your case is with a capitalised i. Use innerHTML not InnerHTML.
To change the alt text, you need to set it first! :)
Set it like this:
<image id="asdfjkl" src="asdf.png" alt="abc">Hello!</image>
Change it like this:
document.getElementById('asdfjkl').alt = 'xyz';
Working Code Snippet:
var image = document.getElementById('asdfjkl');
image.alt = 'xyz';
console.log(image);
<image id="asdfjkl" src="asdf.png" alt="abc">Hello!</image>
For your code, you need to do following 3 things:
Instead of <image> tag use <img> tag.
Wrap your <img> in <figure> and add a <figcaption>.
Instead of fetching the image by ID, fetch the <figcaption> and change its innerHTML.
Thats it!
Working Code Snippet:
var num = 0;
setInterval(function(){document.getElementsByTagName('figcaption')[0].innerHTML="Number: " + num}, 500);
setInterval(function(){num+=1;}, 100);
<figure>
<img id="asdfjkl" src="asdf.png" />
<figcaption>Hello!</figcaption>
</figure>

Javascript gallery with prev/next function AND thumbnail... nothing else

Short of going for something like Galleriffic
and modifying, hiding and removing elements, what would be a way to add a function by which thumbnails can also be clicked to display the image?
Much obliged to anyone who can point me in the right direction. I'm using the following by Paul McFedries at mcfedries.com.
<script type="text/javascript">
<!--
// Use the following variable to specify
// the number of images
var NumberOfImages = 3
var img = new Array(NumberOfImages)
// Use the following variables to specify the image names:
img[0] = "yellow1.jpg"
img[1] = "blue2.jpg"
img[2] = "green3.jpg"
var imgNumber = 0
function NextImage()
{
imgNumber++
if (imgNumber == NumberOfImages)
imgNumber = 0
document.images["VCRImage"].src = img[imgNumber]
}
function PreviousImage()
{
imgNumber--
if (imgNumber < 0)
imgNumber = NumberOfImages - 1
document.images["VCRImage"].src = img[imgNumber]
}
</script>
in the html:
<div class="galleryarrows">
<A HREF="javascript:PreviousImage()">
<IMG SRC="previous.png" BORDER=0></A>
<A HREF="javascript:NextImage()">
<IMG SRC="next.png" BORDER=0></A>
</div>
A quick, basic solution: Save the full size versions of your images in a folder called say, 'full_images', with the same names as the thumbnails.
Add an onClick event into the element img elements that display your thumbnails in the html, so they look something like this.
<img src = "yellow1.jpg" name = "thumb[0]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(0);" alt = "yellow"/>
<img src = "blue2.jpg" name = "thumb[1]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(1);" alt = "blue"/>
<img src = "green3.jpg" name = "thumb[2]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(2);" alt = "green"/>
In your javascript, add this function
function DisplayImage(id){
imgNumber = id;
document.images["VCRImage"].src = "full_images/" + img[id];
}
This will display in an element with the name 'VCRImage'.
Not my favourite solution this, but quick, and should work. If Javascript is new to you, then you might as well check out jQuery. It's a lot easier to use, and is way more cross-browser compatible.

Categories

Resources