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

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>

Related

Rename an img tag and make it self-closing

I would like to change the img tag with amp-img tag without removing the img tag attributes and its value.
Here is my code:
var content = '<div><img src="abcd" height="200" width="210"><img src="bcda" width="50" height="25"></div>';
let replace1 = content.replace(/<img/g, '<amp-img'); //So far so good here
let replace2 = replace1.replace(/>/g, '/>'); // Here I would like to append a close for amp-img only, not for all tag
console.log(replace2)
How can I append close tag for amp-img only?
You can use: <img([^>]+)> and this <amp-img$1/> for replacement.
var content = '<div><img src="abcd" height="200" width="210"><img src="bcda" width="50" height="25"></div>';
let replace1 = content.replace(/<img([^>]+)>/g, '<amp-img$1/>');
console.log(replace1)

JavaScript Function to change HTML not working

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

Generate array of image in javascript inside <div>

I need to make the background image in div tag and it has to change automatically, I already put the array of images inside the javascript, but the images is not showing when i'm run the site.The background should behind the menu header.
This is the div
<div style="min-height:1000px;position:relative;" id="home">
below of the div is containing the logo, menu and nav part.
<div class="container">
<div class="fixed-header">
<!--logo-->
<div class="logo" >
<a href="index.html">
<img src="images/logo.png" alt="logo mazmida" height="142" width="242">
</a>
</div>
<!--//logo-->
This is the javascript
<script>
var imgArray = [
'images/1.jpg',
'images/2.jpg',
'images/3.jpg'],
curIndex = 0;
imgDuration = 2000;
function slideShow() {
document.getElementID('home').src = imgArray[curIndex];
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout("slideShow()", imgDuration);
}
slideShow();
You have a few issues with your script. I've made a live JSbin example here:
https://jsbin.com/welifusomi/edit?html,output
<script>
var imgArray = [
'https://upload.wikimedia.org/wikipedia/en/thumb/0/02/Homer_Simpson_2006.png/220px-Homer_Simpson_2006.png',
'https://upload.wikimedia.org/wikipedia/en/thumb/0/0b/Marge_Simpson.png/220px-Marge_Simpson.png',
'https://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png'
];
var curIndex = 0;
var imgDuration = 1000;
var el = document.getElementById('home');
function slideShow() {
el.style.backgroundImage = 'url(' + imgArray[curIndex % 3] + ')';
curIndex++;
setTimeout("slideShow()", imgDuration);
}
slideShow();
</script>
There are a few issues with your script:
On the element since it's a div not an img, you need to set style.backgroundImage instead of src. Look at https://developer.mozilla.org/en-US/docs/Web/CSS/background for other attributes to related to background image CSS
Also it's document.getElementById
Optimizations
And you can use mod % trick to avoid zero reset
Use setInterval instead of setTimeout
Further optimzations
Use requestAnimationFrame instead of setTimeout/setInterval
I suggest getting familiar with your browser debugging tools which would help identify many of the issues you face.
document.getElementID('home').src = imgArray[curIndex]
You are targeting a div with an ID of home, but this is not an Image element (ie ,
But since you want to alter the background colour of the DIV, then you use querySelector using javascript and store it in a variable, then you can target the background property of this div (ie Background colour).
I hope this helps.
You are trying to change the src property of a div, but divs do not have such property.
Try this:
document.getElementById('home').style.backgroundImage = "url('" + imgArray[curIndex] + "')"
This changes the style of the target div, more precisely the image to be used as background.
As you want to change the background image of the div, instead of document.getElementID('home').src = imgArray[curIndex] use
document.getElementById("#home").style.backgroundImage = "url('imageArray[curIndex]')";
in JavaScript or
$('#home').css('background-image', 'url("' + imageArray[curIndex] + '")'); in jquery.
To achieve expected result, use below option of using setInterval
Please correct below syntax errors
document.getElementID to document.getElementById
.src attribute is not available on div tags
Create img element and add src to it
Finally use setInterval instead of setTimeout outside slideShow function
var imgArray = [
'http://www.w3schools.com/w3css/img_avatar3.png',
'https://tse2.mm.bing.net/th?id=OIP.ySEgAgJIlDQsIQTu_MeoLwHaHa&pid=15.1&P=0&w=300&h=300',
'https://tse4.mm.bing.net/th?id=OIP.wBAPnR04OfXaHuFI9Ny2bgHaE8&pid=15.1&P=0&w=243&h=163'],
curIndex = 0;
imgDuration = 2000;
var home = document.getElementById('home')
var image = document.createElement('img')
function slideShow() {
if(curIndex != imgArray.length-1) {
image.src = imgArray[curIndex];
home.appendChild(image)
curIndex++;
}else{
curIndex = 0;
}
}
setInterval(slideShow,2000)
<div style="position:relative;" id="home"></div>
code sample - https://codepen.io/nagasai/pen/JLKvME

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

passing javascript innerhtml variable to php

Really need your help, I have the below javascript code:
document.querySelector('#btnCrop').addEventListener('click', function(){
var img = cropper.getDataURL();
document.querySelector('.cropped').innerHTML += img;
})
The "img" has a value:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMYAAADGCAYAAACJm/9dAAAgAElEQVR4Xuy9B6CdZZUuvE56771AQgqEGgKEkNCrgoAFRFQQHevM+Ht/nTsX5/7XmXFm1Jlx7HVGZSxIN0iXIqFLSEgIkALpvScnvZ/7rPaW7/v2PicQEPzdGs7eX3nLeldf611vAxE14d+b/rn2/DPos5ddSN26
so what is does in php is to display it via:
$img = (div class="cropped" style="float: left;margin-top:-653px;margin-left: 630px;border:1px solid violet")(/div)
What I need is to display it without div. Just the value of the "img".
Replace
document.querySelector('.cropped').innerHTML += img;
with something like this:
document.write("<img src=\"" + img + "\" style=\"\">");
That will just write it in document. But basically it's the same when extending it to something.
Something like this is more what you want I guess:
$('img#ID').attr('src', img);
(This wil set the src value (Base64) in the image. If you want you could hide it at first and then use $().show() to make the image visible again.

Categories

Resources