I'm a beginner.
I encounter a small problem which is I cannot add an image to my div block.
here is my HTML code
<span class = 'memepic'>
<img src ="https://encryptedtbn0.gstatic.com/imagesq=tbn:ANd9GcTmvCGIVavqB6jVObiS1sqkvwlzYgpjCVfWBg&usqp=CAU">
</span>
and I wrote my js code is like this one
//it is my <span> id
const img = document.getElementsByClassName('memepic')
//it is my divblock id
const memebox = document.querySelector('#meme')
for(i of img){
i.addEventListener("click", function(e) {
console.log(e)
memebox.style.backgroundImage = 'url("e.path[0].currentSrc")';
});
}
the error shows my console is
e.path[0].currentSrc:1 GET file:///C:/Users/kevin/Desktop/bootcamp/officialclass/meme%20generator/e.path[0].currentSrc net::ERR_FILE_NOT_FOUND
my purpose is when I click that picture, that picture will show on my divblock which is in the center of the screen.
I checked the path[0].currentSrc is correct.
and it will show the picture if I replace 'e.path[0].currentSrc' to the content inside the 'e.path[0].currentSrc'.
like this
memebox.style.backgroundImage = 'url("https://encryptedtbn0.gstatic.com/imagesq=tbn:ANd9GcTmvCGIVavqB6jVObiS1sqkvwlzYgpjCVfWBg&usqp=CAU");
Hey can you try this code in for loop :
`url(${e.srcElement.currentSrc})`
Javascript doesn't parse variables that are inside a string, so you're asking for the background URL to literally be set as "e.path[0].currentSrc".
Instead of this:
memebox.style.backgroundImage = 'url("e.path[0].currentSrc")';
Do this:
memebox.style.backgroundImage = 'url("' + e.path[0].currentSrc + '")';
Related
I'm looking for some help writing a javascript snippet that will DYNAMICALLY update a div style= "background-image:url..." to match the a href above it. This is on a portfolio website, so this is a gallery where all the images are live at once. I need the snippet to run through each individual a href and nested div underneath it and have them match, unique to each image (Don't want a page of the same picture 20 times)
I'm just starting to learn JS, so I've been struggling with this one. Here's the html.
<a id ="tobematched" href="imgs/galleryphotos/1.jpg">
This href should from above should be copied to the div style url below.
<div id ="matcher" class="img-container" style="background-image: url('imgs/notcorrect/currently.jpg');"></div>
</a>
This is what it looks like as a whole...
<a id ="tobematched" href="imgs/galleryphotos/1.jpg">
<div id ="matcher" class="img-container" style="background-image: url('imgs/notcorrect/currently.jpg');"></div>
</a>
Any help would be greatly appreciated!
This is what I'm thinking, so far...
function abc() {
var a = document.getElementById("tobematched").
var b = document.getElementById("matcher").style.backgroundImage;
}
Not sure where to go from here, since I don't know how to grab the href... I think I'm on the right track.
You can use a combination of querySelector() and the .href property to get what you need:
var targetDiv = document.querySelector('#matcher');
var url = targetDiv.parentNode.href;
targetDiv.style.backgroundImage = 'url(' + url + ')';
Alternatively you can use:
var url = document.querySelector('#tobematched').href
This second option does not depend on the structure of the document, but causes JS to look through the whole document again.
If you were using jQuery:
var url = $('#tobematched')attr('href');
$('#matcher').css('background-image', 'url(' + url + ')');
Live Example
Edit: As per the further description by OP in the comments, here is the code you actually need:
var targetDivs = document.querySelectorAll('.img-container');
for (var i = 0; i < targetDivs.length; i++) {
var url = targetDivs[i].parentNode.href;
targetDivs[i].style.backgroundImage = 'url(' + url + ')';
}
I have wrote this javascript to show some images with id: imgFotogramma1/imgFotogramma2/ecc.. randomly in 8 different div with id Fotogramma1/Fotogramma2/ecc..:
function rullino() {
var immagini = new Array("strutture/1.jpg", "strutture/2.jpg", "strutture/3.jpg", "strutture/4.jpg", "strutture/5.jpg", "strutture/6.jpg", "strutture/7.jpg", "strutture/8.jpg", "strutture/9.jpg");
for (i = 1; i < 9; i++) {
var x = Math.floor(immagini.length * Math.random(1));
var imgId = "imgFotogramma" + i;
$(function () {
$(imgId).fadeIn(1000);
src = $(imgId).attr('src');
src = immagini[x];
alert(src);
});
}
setInterval("rullino()", 4000);
};
Now,this code start when body is loaded and its repeated every 4 seconds but i don't understand why the images are not displayed. I have started to work with Jquery not too much time ago and probably something are wrong.
I want to specify that: if i use normally javascript to assign to the src attribute the value of immagini[x],all work fine and the images are displayed.I have problem only to apply the fadein() motion.
I need a help to understand where is wrong,i have studied the fadeIn() API and i have tried to apply to my case.
Thanks in advance to anyone want to help me.
$(imgId).fadeIn(1000);
should be:
$('#'+imgId).fadeIn(1000);
Use # + idOfElemnt to select element with particular id.
You already doing it right. Just replace
var imgId = "imgFotogramma"+i;
With
var imgId = "#imgFotogramma"+i;
Since your are using the ID of the image, then your must have to use the "#" for id for applying the jQuery on it.
To select an ID, use # + elemID. Like this:
var imgId = "#imgFotogramma" + i;
Also, fade will not occur if the element is not hidden. First hide it, and then fade it in:
$(imgId).hide().fadeIn(1000);
I have a function in which when the function is called I need to have text and an image pop up. My javascript is:
function Upload(){
if(value !- ''){
$("#divValue").html("Uploaded: " + //i need to add an image here );
}
So where it says //I need to add an image here, this is where my image, lets say its tire.gif, needs to be added so when the javascript is called it displays the text and image together.
you can use document.createElement method to create a img Object and simply set the source and optional height and width, then add it to your div using "append":
var img = document.createElement('img')
img.src = //URL to your image
$(img).css('width','50px'); //set the width (optional)
$(img).css('height','50px'); //set the height (optional)
//finally append the newly created image object to your "DivValue"
$("#divValue").append(img);
Can you try this,
function Upload(){
var value="some value";
if(value != ''){
$("#divValue").html("Uploaded: <img src='../images/tire.gif' />" );
}
}
It is actually pretty straight forward. You just need to pass the tag inside the string that will replace the html.
Check this jsFiddle
But you just need to do:
$("#divValue").html("Uploaded: <img src=' PATH_TO tire.gif ' /> ");
Watch the difference between " and ' to avoid syntax problems.
Cheers.
You mean like this?
$("#divValue").html('Uploaded: ' + '<img src="image.jpg" alt=""/>');
I tested the following code in IE, Chrome, and Firefox and it does not work in any of them. I have read several questions about similar problems but they have not offered solutions that fix my example.
I am trying to create a pause/play button that interfaces with JWplayer (I also want it to interface with flowplayer, once I get the button working) and the image will change depending on which image is currently there. I also have a stop button that stops the player completely and changes the image of the pause/play button to pause.
Here is my current code:
<script type="text/javascript">
function changeimg()
{
var obj = document.getElementById('image1');
var imgtag1 = '<img src=\'PLAY.png\'>';
var imgtag2 = '<img src=\'PAUSE.png\'>';
if(obj.innerHTML == imgtag2)
{obj.innerHTML = imgtag1;}
else
{obj.innerHTML = imgtag2;}
return;
}
function playimg()
{
document.getElementById('image1').innerHTML = '<img src=\'PLAY.png\'>';
return;
}
</script>
<div id="image1" href="#" onclick="changeimg(); jwplayer('mediaspace1').play(); jwplayer('mediaspace2').play(); jwplayer('mediaspace3').play(); jwplayer('mediaspace4').play();"><img src='PLAY.png'></div>
<div href="#" onclick="playimg(); jwplayer('mediaspace1').stop(); jwplayer('mediaspace2').stop(); jwplayer('mediaspace3').stop(); jwplayer('mediaspace4').stop();"><img src='STOP.png'></div>
The play/pause function works, and the first div WILL change into the pause img (so the javascript is going through) and it WILL change back into play if I click on the second div (stop function - triggers playimg() ) but it will not change back into the play image if I click on the pause button again.
For security reasons I can't link the website, but any help would be appreciated
It looks like all you really want to change is the SRC of the IMG tag, not necessarily the entire innerHTML. As machineghost mentions in his comment, there may be whitespace added or other changes to the full HTML that may make your comparison come out as false.
However, you could check if obj.src == "PLAY.png" and set the SRC attribute directly. Something like this:
function changeimg()
{
var obj = document.getElementById('image1');
var img1 = 'PLAY.png';
var img2 = 'PAUSE.png';
if(obj.src == img2)
{obj.src = img1;}
else
{obj.src = img2;}
return;
}
I think the innerhtml you are replacing in changeimg() is affecting the whole obj element, which is a div. So, if(obj.innerHTML == imgtag2) will return false since the div innerhtml is not imgtag2, but the next time you are going to call changeimg(), "obj" will be undefined because you replaced its innerhtml with an HTML code that doesn't have an id: {obj.innerHTML = imgtag2;}
Check the console to see if there's any javascript error, which it should, at if(obj.innerHTML == imgtag2)
rgds.
Just check whether PLAY is present or not and then change innerHTML according to it
function changeimg()
{
var obj = document.getElementById('image1');
var imgtag1 = '<img src=\'PLAY.png\'>';
var imgtag2 = '<img src=\'PAUSE.png\'>';
if(obj.innerHTML.indexOf('PLAY') != -1)
{obj.innerHTML = imgtag2;}
else
{obj.innerHTML = imgtag1;}
return;
}
I have a page with pictures, which I want to displayed in a popup.php when clicking on them.
I want the popup window to display a picture(the one I'm clicking on), some text, and a print button.
I'm doing this on the page:
<img src="graphics/picture1.png" width="340" height="200" border="0"/>
In the JS file:
function popup()
{
window.open('popup.php', 'window', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=520,height=400,left=350,top=100');
}
function showImg(img)
{
var imageSrc = "imageName/imagePath.png";
if(img.src != imageSrc){
img.src = imageSrc;
}
}
And in the popup.php:
<img src="graphics/picture03.png" onload="showImg(this)" />
There should be an obvious way, but I can't find it.
I would think adding the image name and text content to the URL would be the obvious way.
popup.php?image=myImage.gif&text=Say%20something%20witty%20here
Well, you'll want to have your popup contain a holder for the image (which it seems like you already have), but you'll also need to have a holder for your text. Your popup.php should have something like <div id="textHolder"></div> - then your javascript function needs to accept the appropriate text as well as populate it into the textHolder div.
I'm not sure how you're calling these JS functions, or from where - so some of the code might need to change - it should be something to the tune of....
function showImg(img, textHolderObj, text)
{
var imageSrc = "imageName/imagePath.png";
if(img.src != imageSrc){
img.src = imageSrc;
}
textHolderObj.innerHTML= text
}
If is that simple, you could create it:
var win = window.open('', 'win', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=520,height=400,left=350,top=100');
var img = win.document.createElement('img');
img.src = 'image.png';
img.alt = 'Some text';
var label = win.document.createElement('p');
label.innerHTML = 'Some text';
var button = win.document.createElement('a');
button.href = 'javascript:window.close()';
button.innerHTML = 'Close';
win.document.body.appendChild(img);
win.document.body.appendChild(label);
win.document.body.appendChild(button);
I don't get the question too well. You want to access a function that was defined in the page that opened a popup? You should be able to use opener.showImg(this)
your popup has no idea what image you clicked on. you need to do this:
onClick="popup('imgSrc')"
and in your window reference:
window.open('popup.php?imgSrc='+imgSrc, ...
then... your popup window has to run off of url vars, but php now knows what its looking for:
<?php echo '<img src="' . $_GET["imgSrc"] . '" />'; // this is going to load the image, so you don't need the onLoad()
It is possible to create a new popup window using a variable
top.mydocument=window.open('','window','toolbar=no,location=no,
status=no,menubar=no,scrollbars=no,resizable=no,
width=520,height=400,left=350,top=100');
and then use document.write to write the content:
top.mydocument.document.write(
'<html><head></head>'
+'<body bgcolor=white onLoad="self.focus()">'
+'imageName/imagePath.png'
+'</body></html>'
)
Make sure you close it.
top.mydocument.document.close()