I apologise if it sounds similar to a previous question, but I've gone over those similar questions and I still can't figure out what the problem is with my code. it's petty simple yet it doesn't work.
I have an image. I want it to change to a second image when I click on it, and to a third image when I click on the second image. and then, I want it to change back to the first image when the third image is clicked.
html:
<img id="narrow" class="item" src="images/joe2.jpg" style="cursor:pointer" onclick="changeImage(this);">
javascipt:
function changeImage(imgl) {
if(imgl.src=="images/joe2.jpg") {
imgl.src="images/stray_cat.jpg";
}
else if (imgl.src=="images/stray_cat.jpg") {
imgl.src="images/mathewgarber.jpg";
}
else // (imgl.src=="images/mathewgarber.jpg") {
imgl.src="images/joe2.jpg";
}
}
what happens is that nothing happens when I click on the first image. thanks for your help.
Try something like this:
var images = [
'http://lorempixel.com/100/100/nature/1',
'http://lorempixel.com/100/100/nature/2',
'http://lorempixel.com/100/100/nature/3'
],
i = 0;
function changeImage(img) {
img.src = images[++i % images.length];
}
Comparing image src with a string is not very reliable because it can contain full domain and protocol. Instead you can store images in array and use % operator which is very useful for such kind of cycling.
Demo: http://jsfiddle.net/phJA4/
As dsfq above said, the image src url will be relative, including the site host.
function changeImage(imgl) {
if (imgl.src.indexOf('images/joe2.jpg') > -1) {
imgl.src = "images/stray_cat.jpg";
} else if (imgl.src.indexOf("images/stray_cat.jpg") > -1) {
imgl.src = "images/mathewgarber.jpg";
} else // (imgl.src=="images/mathewgarber.jpg")
{
imgl.src = "images/joe2.jpg";
}
}
If you have your heart set on your method, you can use a indexOf check to determine if the image name is part of the full src url.
First of all you have the last { commented out by your imgl.src=="images/mathewgarber.jpg").
Secondly, the img1.src gives you a different string, take a look at this Demo
You should check for the src like this:
if(imgl.src.indexOf("images/joe2.jpg") > -1)
Related
I have an image button and I would like to do that if I click to the img button it is changed, then if I click again to the button it change back to the default image.
I have this script but it doesnt change back. Anybody can help me?
<script>
function VOR2(img)
{
if(img.src.match(/blank/))
{
img.src = "VOR.gif";
}
else
{
img.src = "VOR2.gif";
}
}
</script>
<img src="VOR.gif" id="VOR2" onclick=VOR2
The reason that your code is currently not working is because img.src.match(/blank/) looks if the image source has the text "blank" (the forward slashes make it a regex). However neither images you have provided include the text "blank", so it simply does nothing, and isn't the best use case anyways.
The best practice for this would be toggling a class with classList to your image to help identify which "state" it is in, such as the below:
<script>
function VOR2(img) {
isChanged = img.classList.contains('changed-image');
img.src = isChanged ? 'VOR.gif' : 'VOR2.gif';
img.classList.toggle('changed-image');
}
</script>
<img src="VOR.gif" id="VOR2" onclick=VOR2>
I would also suggest moving the script into a different file.
You could do it this way :
JS :
function VOR2(img) {
if (img.src == "VOR2.gif") {
img.src = "VOR.gif";
} else {
img.src = "VOR2.gif";
}
console.log(img.src);
}
HTML :
<img src="VOR.gif" id="VOR2" onclick="VOR2(this)" />
I am having problems with a javascript function. I want to replace an icon by changing the class.
On my page, I have the following element:
<i class="wait icon" alt="{webui_botstatenotavailable}" title="{webui_botstatenotavailable}" id="{botname}"></i>
The following javascript should change the class, but it does not work:
function incomingBotStatusList(http_request, statusOff, statusOn)
{
if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
if (http_request.responseText.length < 7)
{
// Error
}
else
{
var botStatusList = JSON.parse(http_request.responseText);
for (var key in botStatusList)
{
if (botStatusList.hasOwnProperty(key))
{
var botStatusImage = document.getElementById(key);
if (botStatusImage != null)
{
if (botStatusList[key] == 0)
{
botStatusImage.class.innerHTML = "images/bullet_red.png";
botStatusImage.title = statusOff;
botStatusImage.alt = statusOff;
}
else if (botStatusList[key] == 1)
{
botStatusImage.class.innerHTML = "<i class=\"checkmark green icon\">";
botStatusImage.alt = statusOn;
botStatusImage.title = statusOn;
}
}
}
}
}
}
}
}
Did someone from you know how it will work?
Thanks for your help!
Best Regards
Pierre
I see a couple of problems with your code. First, the <i> element is used to apply italic formatting to text. It is not the HTML code for an icon or an image.
Secondly, you write botStatusImage.class.innerHTML, but the Element.class does not exist, and Element.className is a string. It does not have an innerHTML attribute. So, you could write botStatusImage.className = "new_class_name"; and this would be more correct.
You should then change the image source by calling botStatusImage.setAttribute('src', new_url), where you have set new_url to the new image location.
Check out the javascript reference for the Element class that is returned from document.getElementById: check this link
My recommendation, start simple, then make it complex.
First, try to get the icon to change without the AJAX request. Try writing a function like this:
function changeIcon( imageId, newUrl ){
var element = document.getElementById( imageId );
element.setAttribute( "src", newUrl );
}
Then test this function in the console by passing calling it with the URL's manually.
Once that works, don't change it! Next add the AJAX call, and when you have the Icon url from your server response, all you do is call the function that you already wrote and tested. That way you separate the AJAX code from the image update code and you can test them separately.
The key is smaller functions. Build the easy stuff first, and then call those easy functions from the harder functions. Once you know the easy function works well, it becomes much easier to find problems in the harder functions.
I have some javascript which looks at the body and finds words and if one is present, it outputs a div. This is useful for many things, however...
What I need to do is also look at the body and all the ALT tags for the page as well.
I found this: Use javascript to hide element based on ALT TAG only?
Which seems to change the ALT attribute, however I want to perform an action.
Here's my JS so far.
var bodytext = $('body').text();
if(bodytext.toLowerCase().indexOf('one' || 'two')==-1)
return;
var elem = $("<div>Text Here</div>");
Thank you.
P.S. I am a N00B/ relatively new at JS, I am doing this for a small project, so I am not sure where to start for this in terms of JS functions.
Updated Answer
Try this out, I commented the code to explain it a bit.
// build array of triggers
var triggers = ['trigger1','trigger2','trigger3'];
// wait for page to load
$(function() {
// show loading overlay
$('body').append('<div id="mypluginname-overlay" style="height:100%;width:100%;background-color:#FFF;"></div>');
// check page title
var $title = $('head title');
for(trigger of triggers) {
if($($title).innerHTML.toLowerCase().indexOf(trigger) >= 0) {
$($title).innerHTML = '*censored*';
}
}
// check all meta
$('meta').each(function() {
var $meta = $(this);
for(trigger of triggers) {
if($($meta).attr('name').toLowerCase().indexOf(trigger) >= 0) {
censorPage();
return; //stop script if entire page must be censored
} else if($($meta).attr('content').toLowerCase().indexOf(trigger) >= 0) {
censorPage();
return; //stop script if entire page must be censored
}
}
});
// check all img
$('img').each(function() {
var $img = $(this);
for(trigger of triggers) {
if($($img).attr('alt').toLowerCase().indexOf(trigger) >= 0) {
censor($img);
}
}
});
// check all video
$('video').each(function() {
var $video = $(this);
for(trigger of triggers) {
if($($video).attr('alt').toLowerCase().indexOf(trigger) >= 0) {
censor($video);
}
}
});
// if you want to be extra careful and check things like background image name,
// you'll have to run this code here - very inefficent
// but necessary if you want to check every single element's background image name:
for($element of $('body').children()) {
for(trigger of triggers) {
if($($element).css('background-image').toLowerCase().indexOf(trigger) >= 0) {
$($element).css('background-image','');
}
}
}
, function() { // Not sure if this is totally correct syntax, but use a callback function to determine when
// when the rest of the script has finished running
// hide overlay
$('#mypluginname-overlay').fadeOut(500);
}});
function censor($element) {
// just a basic example, you'll probably want to make this more complex to overlay it properly
$element.innerHTML = 'new content';
}
function censorPage() {
// just a basic example, you'll probably want to make this more complex to overlay it properly
$('body').innerHTML = 'new content';
}
---Original Answer---
I'm not sure exactly what you would like to do here, you should add more detail. However if you choose to use jQuery, it provides tons of useful methods including the method .attr(), which lets you get the value of any attribute of any element.
Example:
var alt = $('#my-selector').attr('alt');
if (alt == 'whatYouWant') {
alert('yay');
} else {
alert('nay');
}
You're using jQuery lib, you could select elements by attribute like:
$('[alt="one"]').each(function(el){
// do something
var x = $(el).arrt('alt');
});
If you use selector $('[alt]') you can get elements that have this attribute set, and then check the value of the element if you have a more complicated selection.
Than you have to change your return, as you could not put a div inside an ALT tag, it didn't work.
Here is about what is your expected output.
UPDATE
As you want to change all images and video in a page, the way to do this with jquery is through $.replaceWith():
$('img,video').replaceWith($('<div>Text Here</div>'));
If you need to filter the elements:
$('img,video').each(function(el){
if($(el).prop('tagName') == 'IMG' &&
$(el).attr('alt') == 'the text...') {
$(el).replaceWith($('<div>Text Here</div>'));
}
})
But I'm not an expert on Chrome Extensions, I just put this code here in jQuery, as you was using jQuery.
Of course it could be done, with much code with plain javascript and the DOM API.
This is my first ever question on here and I figure it must have a simple answer but it's frustrated me for a while, especially since I'm new to Javascript. So I have many images and would like to change to the next one by clicking on it on the webpage, starting with a certain image, obviously. Now I could do this with nested if else statements but if you have many images you get too many ones nested into each other and it can get too complex so I figured there must be a simpler way of doing it. Here's an example of the code I had:
function changeImage()
{
var image=document.getElementById("mainImage")
if (image.src.match("image1.jpg"))
{
image.src="image2.jpg";
}
else if (image.src.match("image2.jpg"))
{
image.src="image3.jpg";
}
else
{
if (image.src.match("image3.jpg"))
{
image.src="image4.jpg";
}
else
{
image.src="image1.jpg";
}
}
}
So you can see it's not the best way to do it. I tried to do it with a switch statement but I couldn't either (and would appreciate it if someone told me if it could be done with one and how). As a last try I tried this but for some reason it jumps from image1 to image4 at once:
function changeImage()
{
var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]
var myImage = document.getElementById("mainImage")
for (i=0; i < images.length; i++)
{
if (myImage.src.match(images[i]))
{
myImage.src = images[i+1]
}
}
}
So I could really appreciate some help. Thanks in advance.
Your last changeImage goes to #4 immediately because you're changing the image in the for loop which causes the check within the loop to keep being true and so it runs all the way to the last index, at which point the check finally fails. Instead, you'll want to maintain the current image index with a variable. Then, just change myImage.src to images[currentIndex + 1] on each click. Try something like below. You'll want to run showNextImage on page load and then run it once each time the image is clicked.
<script>
var currentImageIndex = 0;
//Cycle through images
showNextImage() {
var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]
var myImage = document.getElementById("mainImage")
myImage.src = images[currentImageIndex];
currentImageIndex++;
if(currentImageIndex >= images.length)
currentImageIndex = 0;
}
</script>
not sure if this is possible keeping the code simple, but im trying to make it so that i have an image, when you clicked it, it goes to a new image. then when you click that image, it goes back to the original image.
my code is:
function save_data()
{
if ( document.images.save.src == "saved.png") document.images.save.src="save.png";
if (document.images.save.src == "save.png") document.images.save.src="saved.png";
}
<img id="save" onclick="save_data()" src="save.png">
It can be simplified.
Using
<img id="save" onclick="save_data(this)" src="save.png">`
You can do
function save_data(img)
{
img.src = /saved/i.test(img.src) ? 'save.png' : 'saved.png';
}
If this doesn't work, it may have to do with the fact that saved.png is not in the path the html is in. So try it with a full URL:
function save_data(img)
{
var imgpath = 'http://yoursite.com/imgpath/';
img.src = imgpath + (/saved/i.test(img.src) ? 'save.png' : 'saved.png');
}
A note: it may be better to assign the click handler unobtrusively (see also this SO question)
if ( document.images.save.src == "saved.png") - this won't work, because .src returns the full path to the image, not just the filename. For example, http://site.com/path/images/saved.png.
Try matching substrings instead.
function save_data()
{
if ( document.images.save.src.indexOf("saved.png") != -1) document.images.save.src="save.png";
if (document.images.save.src.indexOf("save.png") != -1) document.images.save.src="saved.png";
}