I don't know why, but my Javascript only works once in Firefox and IE (but it works fine in Chrome). Does anybody know why?
<script type="text/javascript">
function changeDivImage()
{
var imgPath = new String();
imgPath = document.getElementById("div1").style.backgroundImage;
if (imgPath == "url(images/1.jpg)" || imgPath == "")
{
document.getElementById("div1").style.backgroundImage ="url(images/2.jpg)";
}
else if (imgPath == "url(images/2.jpg)")
{
document.getElementById("div1").style.backgroundImage = "url(images/3.jpg)";
}
else if (imgPath == "url(images/3.jpg)")
{
document.getElementById("div1").style.backgroundImage = "url(images/1.jpg)";
}
}
</script>
Script is triggered by clicking on image
<img src="images/leftarrow.png"
value="Change Background Image"
onclick="changeDivImage()" />
Browsers tend to normalise CSS properties in different ways. IE and Firefox put quotes around the URL, for instance.
So, perhaps you should try this instead:
var div = document.getElementById('div1'),
imgPath = parseInt(div.style.backgroundImage.match(/\d(?=\.jpg)/) || ["0"],10),
newnum = imgPath%3+1;
div.style.backgroundImage = "url(images/"+newnum+".jpg)";
Related
i was trying to make a facemash like site using js. But when i click on an image is not changing the images rightly. its sometime showing same images in both the img elements. here the js code i use for selecting images when clicked.
function changeEle(id) {
var otherSrc = id == 0? imageElements[1].src : imageElements[0].src;
var ele = imageElements[id];
var oldSrc = ele.src;
var newSrc = randomFromArray(imagesList);
while(newSrc == oldSrc || newSrc == otherSrc) {
newSrc = randomFromArray(imagesList);
}
ele.src = newSrc;
}
imageElements[0].onclick = function() {
changeEle(1);
}
imageElements[1].onclick = function() {
changeEle(0);
}
Check what oldSrc and otherSrc contain with a debugger or console.log(). I think you'll find that the values aren't exactly the same as the original values in imagesList, so that when you do the comparison (newSrc == oldSrc || newSrc == otherSrc) images that are the same image as far as you're concerned manage to slip by.
I have a lightbox which is getting the background image of another div and then stripping the url() to then put the link inside of an which is working in all browsers except Firefox and can't work out why this would be happening, in Firefox for me it is adding '' around the "" within the src which is breaking the link.
_getImagePath: function($el) {
var imagePath,
spanEl = $el.find('span.js-cell-image-background'),
imgEl = $el.find('img.cell-image__image');
if(spanEl.length) {
imagePath = spanEl.css('backgroundImage');
imagePath = imagePath.replace('url(', '').replace(')', '');
} else if(imgEl.length) {
imagePath = imgEl.attr('src');
}
return imagePath;
},
Just remove the "" as you do the brackets:
imagePath = imagePath.replace('url(', '')
.replace(')', '')
.replace(/^"/, '')
.replace(/"$/, '')
or in one:
imagePath = imagePath.replace(/^url\(\"?/, '').replace(/\"?\)$/, '')
As you've found, the backgroundImage property is browser-dependent. As an example, I have a site, opened in 3x browsers, opened console and typed:
$(".icon-home").css("backgroundImage")
Chrome:
"url(http://..url../images/home.png)"
Firefox:
"url("http://..url../images/home.png")"
IE10:
"url("http://..url../images/home.png")"
Thank you for the reply freedomn-m I managed to solve this a few minutes before you posted by just changing this line:
imagePath = imagePath.replace('url(', '').replace(')', '');
To this:
imagePath = imagePath.replace(/url\(["]*/,'').replace(/["]*\)/,'');
Thanks,
Luke.
So I am having issues with captioning my slide show using a javascript, can somebody let me know as to where I am going wrong. My code stands as this:
JavaScript Document
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
var img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
if( img.attr("src") == "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.attr("src") == "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.attr("src") == "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.attr("src") == "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.attr("src") == "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
HTML document
<div class="slides">
<img id="img1" src="">
</div>
<input type="image" src="images/Next.png" id="button" onClick="javascript:moveToNextSlide()" title="Next" >
<div id ="captionbar"></div>
Also to note, that I get this error within the "inspect element":
Uncaught TypeError: Cannot call method 'attr' of null
REVISED
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
window.onload = function(){
if( img.src === "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.src === "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.src === "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.src === "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.src === "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
}
The HTML Remains the same as before.
No error references however function does not write the text whatsoever.
Replace all img.attr('src') by img.src=="your image name".
For example:
img.src=="movieImages/img1.jpg"
As you are using pure JavaScript,you cannot use attr() which is method of JQuery.
attr() is a method brought by JQuery. If you are not using JQuery, you should keep using img.src. Another thing I noticed that might cause trouble : when you read .src from your image, you get the full path as a return (including your domain).
Your conditions would then become :
img.src === "http://yourdomain.com/movieImages/img1.jpg"
( And I just checked to be sure : http://www.w3schools.com/jsref/prop_img_src.asp mentions that the return value of img.src includes protocol and domain )
Also I think you should either define your function CaptionSlide inside moveToNextSlide so that it gains access to the updated img variable or not declare your img variable inside the moveToNextSlide function (so that the global variable gets updated instead)
Another point : you should make sure the DOM is loaded before querying elements from it (such as img) . To do so, wrap your code in a function, and assign it to the window.onload event :
window.onload = function() {
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
...
}
function CaptionSlide()
{
if( ... )
...
}
document.getElementById("button").addEventListener('click', moveToNextSlide);
}
and HTML for button :
<input type="image" src="images/Next.png" id="button" title="Next" />
This code works fine in firefox, when Search button clicked, an image pops inside the myText box, right aligned:
function showImg(){
var setStyle = document.getElementById('myText').style ==
"background-color:white" ?
document.getElementById('myText').style =
"background: url(/somePath/someImg.gif) no-repeat; background-position:right; background-color:white" :
document.getElementById('myText').style == "background-color:white";}
<input type="text" id="myText">
<input type="button" value="Search" onClick="showImg()">
but in IE8 throws "Member not found". it's definitely related to setting the style, but i can't figure how to get around it
thanks for any help
#
thanks everybody for answering. cssText works when trying to detect an existing style string, but not when trying to set it (won't throw an error, but no image either). If i try to use style= to set it, i get the Member not found error. That makes me think that trying to preload the image with visibility:hidden woudn't work either
function showImg(){
if (document.getElementById('myText').cssText = "background-color:white"){
alert("style detected"); // this works
document.getElementById('myText').cssText="background: url(/somePath/someImg.gif) no-repeat; background-position:right; background-color:white"; // this doesn't
} else { alert("style not detected"); }}
<input type="text" id="myText" style="background-color:white">
<input type="button" value="Search" onClick="showImg()">
#
i found kind of a solution, works as a toggle in IE8 (img appears/disappears onClick inside text box). However, in firefox, it appears/disappears only once (!) then does nothing. Would somebody know how to fix that?
i've created a second, invisible image (one pixel, transparent), and i'm switching them
picShow=new Image();
picShow.src="/somePath/realImage.gif";
picHide=new Image();
picHide.src="/somePath/invisibleImage.gif";
function showImg() {
var imgPath = new String();
imgPath = document.getElementById('myText').style.backgroundImage;
if (imgPath == "url(/somePath/invisibleImage.gif)" || imgPath == "") {
document.getElementById('myText').style.backgroundImage = "url(/somePath/realImage.gif)";
document.getElementById('myText').style.backgroundRepeat="no-repeat";
document.getElementById('myText').style.backgroundPosition="right";
} else {
document.getElementById('myText').style.backgroundImage = "url(/somePath/invisibleImage.gif)";
}
}
#
ahhh, firefox creates the backgroundImage putting the url within double quotes, like url("/somePath/invisibleImage.gif"), but IE doesn't. just have to escape them for firefox. this is the working code, just in case someone else needs it. Thanks again everybody!
picShow=new Image();
picShow.src="/somePath/realImage.gif";
picHide=new Image();
picHide.src="/somePath/invisibleImage.gif";
function showImg() {
var imgPath = new String();
imgPath = document.getElementById('myText').style.backgroundImage;
if (imgPath == "url(/somePath/invisibleImage.gif)" || imgPath == "url(\"/somePath/invisibleImage.gif\")" || imgPath == "") {
document.getElementById('myText').style.backgroundImage = "url(/somePath/realImage.gif)";
document.getElementById('myText').style.backgroundRepeat="no-repeat";
document.getElementById('myText').style.backgroundPosition="right";
} else {
document.getElementById('myText').style.backgroundImage = "url(/somePath/invisibleImage.gif)";
}
}
Where you have used .style use .cssText instead.
Example:
document.getElementById('myText').cssText == "background-color:white";
The problem is you can not set the style like that and using a ternary operator like that is a bad idea. You would need to use cssText.
var elem = document.getElementById('myText');
var style = (elem.cssText == "background-color:white" ? "background: url(/somePath/someImg.gif) no-repeat; background-position:right; background-color:white" :
"background-color:white";
elem.cssText = style;
A better solution is just setting a CSS class and have a rule in your stylesheet that corresponds.
var elem = document.getElementById('myText');
var className = (elem.className=="active") ? "" : "active";
elem.className = className;
and the CSS
#myText{
background-color: #FFFFFF;
}
#myText.active {
background: url(/somePath/someImg.gif) no-repeat;
background-position:right;
}
firefox creates the backgroundImage putting the url within double quotes, like
url("/somePath/invisibleImage.gif"), but IE8 doesn't. just have to escape them for firefox. this is the working code, just in case someone else needs it.
picShow=new Image();
picShow.src="/somePath/realImage.gif";
picHide=new Image();
picHide.src="/somePath/invisibleImage.gif";
function showImg() {
var imgPath = new String();
imgPath = document.getElementById('myText').style.backgroundImage;
if (imgPath == "url(/somePath/invisibleImage.gif)" || imgPath == "url(\"/somePath/invisibleImage.gif\")" || imgPath == "") {
document.getElementById('myText').style.backgroundImage = "url(/somePath/realImage.gif)";
document.getElementById('myText').style.backgroundRepeat="no-repeat";
document.getElementById('myText').style.backgroundPosition="right";
} else {
document.getElementById('myText').style.backgroundImage = "url(/somePath/invisibleImage.gif)";
}
<input type="text" id="myText">
<input type="button" value="Search" onClick="showImg()">
I am trying to get a background image to change based on a setting in the database, for right now I'm just trying to get a a way of simply modifying the image used without using the data base but I'm hitting a snag. Without the javascript the image appears fine, with the javascript it is simply not there; leading me to believe there is an issue finding the path written to the css.
Thanks in advance for any help!
<script type="text/javascript" language="javascript">
function changecss(myclass, element) {
var CSSRules
var link1 = "url('../../graphics/MainMenuBG0.gif')";
var link2 = "url('../../graphics/MainMenuBG1.gif')";
if (document.all) {
CSSRules = 'rules';
}
else if (document.getElementById) {
CSSRules = 'cssRules';
}
for (var i = 0; i < document.styleSheets[0][CSSRules].length; i++) {
if (document.styleSheets[0][CSSRules][i].selectorText == myclass) {
if (document.styleSheets[0][CSSRules][i].style[element] == link1) {
document.styleSheets[0][CSSRules][i].style[element] = link2;
} else {
document.styleSheets[0][CSSRules][i].style[element] = link1;
}
}
}
}
</script>
You should try something like this :
if (document.styleSheets[0][CSSRules][i].style.getProperty('background-image') == link1) {
document.styleSheets[0][CSSRules][i].style.setProperty('background-image', link2);
} else {
document.styleSheets[0][CSSRules][i].style.setProperty('background-image', link1);
}