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()">
Related
Sorry, I am new to stack overflow so hope I am doing this correctly.
I have the following code:
{
if (session.findById("T1").text == "") {
document.getElementById("W1").style.display = 'none';
} else {
document.getElementById("W1").style.display = 'inline';
}
}
Basically it is saying if T1 is blank, then W1 should not show. If T1 is not blank, W1 will show.
I can't get it working and then tried this by itself:
document.getElementById("W1").style.display = 'none';
What happens is the item quickly disappears (flashes) but then comes back again. So it's kind of working but I want it to stay permanently hidden. Unless of course T1 contains text and then it should reappear.
How can I resolve?
Thanks!!
hey look at my example
function isEmpty() {
var sample = document.getElementById("sample");
var div = document.getElementById("divko");
if (sample.value.trim() == "") {
div.setAttribute("style", "display:none;");
} else {
div.removeAttribute("style");
}
}
<input id="sample" name="sample" onkeyup="isEmpty()">
<div id="divko" style="display:none;">Sample</div>
you can use following hide option
document.getElementById("W1").style.display = 'block';
I've been trying to create an auto complete function for text boxes wherein the user enters the first few characters and the system shows them a list of entries that begin with the user's given input. These entries are fetched from the database and displayed in the UI through javascript. It all works perfectly except in good ol' Internet Explorer where the style sheet properties don't work on the p elements created by javascript. Could anyone please tell me what I'm doing wrong here? Here is the code I'm using
HTML/JSP
<table>
<tr>
<td nowrap>WO Number</td>
<td style="text-align:left;">
<html:text property="won" styleClass="epntextBox" onkeyup="autokom();" styleId="won"/>
<div id="wondiv"></div>
</td>
</tr>
</table>
Javascript (This is some long code. It works fine though...)
function autokom(){
var number = document.getElementById("won").value;
var url = "Fetch_Won?wonnum="+number;
while(document.getElementById("wondiv").hasChildNodes()){
document.getElementById("wondiv").removeChild(document.getElementById("wondiv").childNodes[0]);
}
if(number=="" || number==null){
return false;
}
if(window.XMLHttpRequest)
{
req = new XMLHttpRequest();
try
{
req.open("GET",url,true);
}
catch(e)
{
alert(e);
}
req.onreadystatechange = processfetchWON;
req.send(null);
}
else if(window.ActiveXObject)
{
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.open("GET", url, true);
req.onreadystatechange = processfetchWON;
req.send(null);
}
}
}
function processfetchWON(){
if (req.readyState == 4)
{
if (req.status == 200)
{
try{
var responseXML = req.responseXML;
var parents = responseXML.getElementsByTagName("won");
var won;
var wondiv = document.getElementById("wondiv");
var num = 0;
if(parents.length>=15){
num = 15;
}else {num = parents.length;}
for (var loop = 0; loop < num; loop++)
{
won = parents[loop].childNodes[0].nodeValue;
var p = document.createElement("p");
p.setAttribute("class", "wonp");
p.setAttribute("id", won);
p.onclick = function() { setwon(this.id); };
p.innerHTML = won;
wondiv.appendChild(p);
}
}catch(e){
alert("Exception in fetching WON/ SWON numbers");
}
}
}
}
function setwon(swon){
document.getElementById("won").value=swon;
while(document.getElementById("wondiv").hasChildNodes()){
document.getElementById("wondiv").removeChild(document.getElementById("wondiv").childNodes[0]);
}
}
CSS
#wondiv{ /*This part works just fine*/
position: absolute;z-index:2;
}
.wonp{ /*But the following doesn't*/
display:block;
margin:0px;
padding:4px;
border:1px inset #000000;
cursor: pointer;
background: white;
width:123px;
}
.wonp:hover{
background: #cbcbcb;
}
I haven't had any problems with the javascript code but the style sheet not being applied to the dropdown by IE(8 - 11) is driving me nuts! Someone please help. I'm at the end of my wits here. (The same css works fine for elements that haven't been js created)
Change
p.setAttribute("class", "wonp");
to
p.className = "wonp";
Some versions of IE have a bug in that they expect you to use "className" with setAttribute, even though the attribute's name is class, not className. But all versions of IE and other browsers use className for the reflected property name, so the change above will solve the problem.
It's rare to actually need to use setAttribute. Virtually all of the attributes you might set (with the obvious exception of data-* attributes) have reflected properties on the element instance that are more useful. class and for (as in, on label elements) have slightly odd names (className and htmlFor) because class and for are reserved words in JavaScript and when this was being defined, JavaScript didn't let you use reserved words as property name literals (it does now), but most other reflected properties have the same name as the attribute they reflect:
element.setAttribute("class", x) => element.className = x
labelElement.setAttribute("for", x) => labelElement.htmlFor = x
element.setAttribute("id", x) => element.id = x
formElement.setAttribute("target", x) => formElement.target = x
linkElement.setAttribute("rel", x) => linkElement.rel = x
element.setAttribute("src", x) => element.src = x (script, img, ...)
Sometimes there are slight differences. For instance, element.getAttribute("href") will give you the actual text of the href attribute, but element.href will give you the resolved version (e.g., relative paths expanded to full ones). Similarly, the value property of input elements is only initialized from the "value" attribute, after which it takes on a life of its own (usually, but not always, reflected as defaultValue).
What is the correct way to check if a particular element has a background-image associated with it, in pure Javascript?
Right now I have this:
var elementComputedStyle = window.getComputedStyle(element);
var hasBGImage = elementComputedStyle.getPropertyValue('background-image') !== 'none'
What you have works, but there are alternate ways of finding the property that you might find easier. I don't believe there is a single 'correct' way to do it, however.
Just javascript:
var hasBGImage = element.style.backgroundImage !== '';
Using jQuery:
var hasBGImage = $(element).css('background-image') !== 'none';
Make sure you declare the background image "inline", otherwise .style.backgroundImage won't work.
<script>
window.onload=function() {
var bg = document.getElementById('el').style.backgroundImage.length!=0;
alert(bg);
}
</script>
<div id='el' style="background-image: url('a.jpg');"></div>
If you can use inline CSS, that's the way. If, for some reason, you can't use that, let me know, I'll try to find out something else :)
I used this code in last one project and works perfect
// Check all background images exists
var imageURLs = $('.image-container ');
imageURLs.each(function(index, element){
var imageURL = $(element).css('background-image').replace('url("', '').replace('")', '');
var img = new Image();
img.onerror = function() { $(element).css('background-image','url(/build/images/missing-image.svg)'); };
img.src = imageURL;
});
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" />
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)";