javascript, condition in if statement for recognizing image src - javascript

I'm having a problem getting the condition in this if statement to work, i've tried getElementById & src.indexOf but I am still very new to this. I am trying to replace the blank/ball image with the x/pikachu image only if the blank image is currently showing, so if there was one of the other images there it wouldn't replace it. It doesn't seem to recognize the condition I have in there as true, any idea why?
i've also tried:document.getElementById(bn).src=blank & document.images[bn].src==blank & document.pokemon.bn.src==blank
looking for a way to verify if the current source of the image is the var blank.
thank you
var x = "pikachu.jpg";
var o = "Meowth.jpg";
var blank = "ball.jpg";
function b1Move(imageName){
temp2=imageName;
if(document.pokemon[temp2].src==blank)
document.pokemon[temp2].src=x;
cMove();
}
and the html for the images looks like this:
<a href="javascript:b1Move('b1')"><img src="ball.jpg" height=150 width=150 name=b1
id =b1 > </a>

The src property gives the fully resolved URL. You probably want to use the src attribute, which stays the same:
if( document.pokemon[temp2].getAttribute("src") == blank)
document.pokemon[temp2].setAttribute("src",x);

you should try
if(document.pokemon[temp2].src.indexOf(blank) != -1)
since src is the full url.. then you can check it it contains your image name

Related

trying to grab image url within div's children

I'm making an extension that grabs an image URL within the "uCW" div on an HTML page.
Currently, I have:
var uCW = jNode.closest("div._q7o");
var image = uCW[0].children[1].getElementsByTagName("img")[0].src;
console.log(image);
That finds the image by going into the div/children and pulling the image. Unfortunately, this method is problematic, since it stops working if the children change, which they regularly do.
Instead, I want to select the image by searching the div and all its children (there are a lot of them) for the first image/string that starts with "https://external" (all the images I want start this way, and that doesn't seem to change.)
This is what I tried:
var uCW = jNode.closest("div._q7o");
var image = $(uCW).find([name^="https://external"]).src;
console.log(image);
This doesn't work. The console just prints "undefined."
You could do it like this, if ucw is a classname (if it's an id, you would write $("#ucw") instead):
var image = $(".ucw").find('[src^="https://external"]').attr("src");
console.log(image);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ucw">
<img src="https://external/1.jpg"/>
</div>
If your images have a name attribute with the source of the image as value, you can also adjust your attempt to fetch the images via their name attribute like you did:
var image = $(".ucw").find('[name^="https://external"]').attr("src");

Random image with javascript doesnt want to give the src

I want to show a random picture with every refresh but I don't know why my code is not working... probably because I'm bad at javascript, haha.
I tried "3" instead of "imgs.length", but it's still not working - I too don't really want to give an exact number, because the image count may vary.. only for my example I use three images.
var imgs = ['img1','img2','img3'];
function getRandomImage(){
var rnd = Math.floor(Math.random()*imgs.length);
document.getElementById('pr_randImage').src = imgs[rnd];
}
</script>
<img id="pr_randImage">
Quellcode is just not showing any src at all for the img. What am I doing wrong? I'm thankful for every help.
change this
var imgs = ['img1','img2','img3'];
to something like this depending on extension of the image you are using
var imgs = ['img1.png','img2.png','img3.jpg'];
If that still doesn't work then you need to include the path of where the images are
Something like this
document.getElementById('pr_randImage').src = "/images/" + imgs[rnd];

Get image src without loading the image?

I have a html snippet being returned through ajax. The snippet is an <img> tag.
<img src="image.jpg" />
I need to extract the value of the src attribute without loading the image initially. The reason for this is the src attribute contains a partial path that I need to manipulate in my app to load the image properly.
I have the following code currently extracting the src attribute:
var src = $(value).attr('src');
However, this causes the image to load, resulting in a 404. I would like to avoid this unnecessary request.
How can I extract the value of the src attribute without causing the browser to load the image?
I solved this by changing the name of the src attribute before loading it into jquery.
value = value.replace('src', 'data-src');
var src = $(value).attr('data-src');
Doing this allows me to extract the value without causing the browser to attempt to load the images.
Your best bet is probably to output a data tag on the image. You can then manipulate this using jQuery and then use it to write the final image path.
So you'd do something like this in your HTML:
<img data-img-src="abc.jpg" class="my-image" />
Then in your jQuery:
var path = $('.my-image').data('img-src');
console.log(path); // Do something here, then write the new path with:
$('.my-image).attr('src', new_path);
EDIT: Sorry I just re-read the bit where it's coming via AJAX. In that case, you can probably use the data callback of your ajax request to strip the src from the image.
$.ajax('someURL.html', function(data){
var html = data.replace(/\ssrc/g, ' data-src'),
img = $(html),
src = 'some/path/' + img.data('src');
img.attr('src', src);
$('#container').append(img);
});
If you just have the string , like <img src="image.jpg" /> why dont you go for regex?
Something like: /[\"\'][a-z0-9A-Z\.]*/.
PS:My regex skills are poor,so you could manipulate it accordingly.
Use
var string = '<img src="image.png">';
var matches = string.match(/src\=("|')(.*?)\1/);
console.log(matches[2]);
You can simply remove the attribute after accessing it.
This will not load the invalid image, as you can confirm in your console:
var s= $('<img src="invalidURL.jpg">'),
src= s.attr('src');
s.removeAttr('src');
console.log(src);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Remove removeAttr(), and it will attempt to load the image.

Incorporating a javascript variable in a file path

I am developing a page to display an image, dependent on what the user has previously chosen from a menu. The name of the .jpg is passed in as a parameter ('photo') on the URL and I have been able to parse this as a global variable (myphoto). The .jpgs are all held in one folder.
I now need to do something like (I guess) quoting the image source as being
"myfolder/"+<script>document.write(myphoto)</script>
but this is not working. Any ideas please?
(Image tag changed here to get round the anti-spam.)
BTW all client-side javascript. It's been a few years since I've used this!
You can do the opposite and output the whole image tag in javascript:
<script language="javascript">
document.write('<img src="myfolder/' + myphoto + '" />')'
</script>
It's not working because when the browser sees this line: <img src="myfolder/"+<script>document.write(myphoto)</script>, it's treating the + character as a character and not an operator.
You will need to programmatically set the src of the image. Something like this:
document.getElementById("myImage").src = "myfolder/" + myphoto;
or with jQuery:
$("#myImage").attr("src", "myfolder/" + myphoto);
document.getElementById("imgtagid").src = "your image folder/" + selectedPhoto

Changing IMG SRC with Javascript

I'm new at javascript and while there are many more complex solutions, I don't understand them and hope I don't have to at this point.
I have a main picture...
<img src="main-picture.jpg" name="Mainpic" id="image">
...and I want to be able to change this picture when I click on one of two thumbnails.
<img src="replacement1.jpg" name="pic1">
<img src="replacement2.jpg" name="pic2">
My javascript code I thought would be super easy. I'm currently using...
function FirstPic(){
document.Mainpic.src = document.pic1.src
return
}
function SecPic(){
document.Mainpic.src = document.pic2.src
return
}
Now the variable is changing however it's not staying changed. When the thumbnail is clicked on, the replacement picture flashes on the screen and then it returns to the original main-picture.jpg.
How do I make the change permanent until a different thumbnail is clicked?
Thanks!
I think it's flipping back because your page is reloading.
You need to return false from your onclick= if you don't want the href= value to activate after your onclick.
Also, you can set href="#" just in case. # goes nowhere (doesn't ever reload the page)
I think your page is refreshing by your click, change your links as :
<img src="replacement1.jpg" name="pic1">
<img src="replacement2.jpg" name="pic2">
Why not do something like this (haven't checked the syntax completly, so it could be faulty.
function FirstPic()
{
var pic1 = document.getElementById("pic1");
if (pic1 == typeof('undefined')) return;
pic1.src = "newpicname.jpg";
}
Make sure you give the tags an ID attribute called pic1 and pic2 (instead of a name attribute) and give the image itself an 'onclick' attribute...
<img onclick='FirstPic()' id='pic1' src='image1.jpg' />

Categories