Javascript working on Firefox but not in Chrome and IE6 - javascript

I have javascript that working fine in Firefox 3.x.x, but it does not work in IE*, Chrome, Safari. Simple alert work before calling function. Here is the code
function showDiv(div){
//alert(div);
document.getElementById(div).style.visibility='visible';
document.getElementById(div).style.height='auto';
document.getElementById(div).style.display='block';}
function hideDiv(div){
//alert(div);
document.getElementById(div).style.visibility='hidden';
document.getElementById(div).style.height='0px';
document.getElementById(div).style.display='none';
}
here is the html page code
<td align="center"><a onclick="showDiv('<?=$val['keyname']?>')" style="cursor:pointer;">Edit</a></td>
if I put alert() before showDiv('<?=$val['keyname']?>') then alert box is displayed but the function is not called in other browsers other than fire fox
Please tell me the solution for this.

The syntax looks okay to me.
Make sure there are not multiple elements with the same ID in the document and that your element IDs are valid.

There is nothing inherently wrong in the code you have posted. I suggest you post a reproduceable non-working example: the problem will be elsewhere in the page. Maybe the div ID string isn't unique (this is invalid HTML and will make behaviour unreliable); maybe there's some other script interfering, maybe you have event code firing this that's not written in a cross-browser way
However your attempts to hide an element in three different ways seem like overkill to me. Just a single display change would do it fine.
Another way to do it is to set className='hidden' or '', and use a CSS rule to map that class to display: none. The advantage of this is that you don't have to know whether the element in question is a <div> (that should revert to display: block), a <span> (that should revert to display: inline) or something else. (The table-related elements have particular problems.)

Maybe you could try that:
function showDiv(div) {
var obj = document.getElementById(div);
if (obj) {
obj.style.display = "block";
obj.style.height = "auto";
} else {
alert("DIV with id " + div + " not found. Can't show it.");
}
}
function hideDiv(div) {
var obj = document.getElementById(div);
if (obj) {
obj.style.display = "none";
} else {
alert("DIV with id " + div + " not found. Can't hide it.");
}
}
Do not call document.getElementById several times in the same function, use a variable to store the div element.
The if (obj) test will only execute the code if it has been found by document.getElementById(...).

Related

Global function not executing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have script that creates a div and adds a function that would remove this div on click, but it's not working.
function del(el) {
$("#"+el).remove();
}
function create() {
var element = document.createElement("div");
var att = document.createAttribute("onclick");
att.value = "del(this.id)";
element.setAttributeNode(att);
$(element).attr('id', "someID");
document.getElementById("someContainer").appendChild(element);
}
Yes, yes, I KNOW this is not the best way to add a function, but I want to do it this way.
Just FYI - after executing create() the DIV appears fine. I checked and it does have proper ID and onclick="del(this.id)" attribute, but after clicking on it nothing happens. I double checked and added alert("I'm working") to the onclick attribute later and that worked. I'm not getting any errors. In the past .remove() was working fine but now it doesn't (Maybe that's because of the way I'm adding a function this time)
EDIT: It appears that del() is not executed when clicking on div.
You have this posted with jQuery, but you're showing mostly Vanilla. As to your initial problem,
function del(el) {
$("#"+el).remove();
}
function create() {
var element = document.createElement("div");
var att = document.createAttribute("onclick");
att.value = "del(this.id)";
element.setAttributeNode(att);
$(element).attr('id', "someID");
document.getElementById("someContainer").appendChild(element);
$(element).html('<h1>DIV CREATED!</h1>').css('background-color', String.randColorHex());
}
create();
#someContainer > div { height: 10em; width: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/String.randColorHex/0c9bb2ff/String.randColorHex.js"></script>
<div id="someContainer"></div>
Seems to work fine.
My guess would be that you have an issue with creating multiple divs by with the same ID, or possibly a scope issue.
Here's a couple steps you might take to double check the issue if using Google Chrome Dev Tools:
Open Console
Double Check function 'del' is globally available and the method you expect it to be by simply typing del. If you get an error, then your method may be displaced.
Another way you could check would be put the following in your onClick: try{console.debug(del);}catch(err){console.error('DEL DOES NOT EXIST!')}
Once you've established the method is within scope, if still not working, try the following:
Replace $("#"+el).remove(); with console.debug(el, $('#'+el))
This does a couple of things: It shows you that the Function is working, as well as gives you information of what's going on within.
If the first part of the console message (el) is the ID you expect, then check the 2nd part ($('#'+el)).
It should look something like: [div:#someID]
Open it and check it's length'. If0`, then it did not find that element.
If 1, then remove should be working fine. Put remove back in just above this console call, and ensure you now get a length of 0
Just FYI, this is how to do what you're trying to do using jQuery.
function create() {
var container = $('#someContainer'), // get container
// create div, everything in {} is an ATTR, then append it TO the container
div = $('<div />', { id: 'someID' + container.children('div').length+1 }).appendTo(container);
// just for visual, i use my own plugin to set a random background color
div.css('background-color', String.randColorHex());
}
$(function() {
$(document) // your click methods
.on('click', '#btnCreate', create)
.on('click', '#someContainer > div', function(e) { $(this).remove(); })
// trigger button once on load
$('#btnCreate').trigger('click');
})
#someContainer > div { height: 2em; width: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/String.randColorHex/0c9bb2ff/String.randColorHex.js"></script>
<button id="btnCreate">Create</button>
<hr />
<div id="someContainer"></div>

Calling two functions from same onclick failure

I have a problem when calling 2 JS functions that work fine separately. I am not well versed in JS: I took the scripts from some posts here and adapted them, and I cannot make them work together. My goal is to make appear the side panel and to change the color of a box within that panel when clicking on the related link in the main text (and to undo it by clicking again on it).
This is the function that I use for showing the side panel:
function showRightPanel() {
var elem = document.getElementById("right-panel");
if (elem.classList) {
console.log("classList supported");
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
And this is the function for changing the color:
var els = document.getElementsByClassName('change-color'),
target = document.getElementById('footnotes'),
changeColor = function() {
target.style.backgroundColor = this.getAttribute('data-color');
};
for(var i=els.length-1; i>=0; --i) {
els[i].onclick = changeColor;
}
And this is the html that calls both functions it:
<a href="#footnote1-chapter1" class="change-color" data-color="#E0FFC2"
onclick="showRightPanel();changeColor();"></a>
And this is the box that has to appear and change color:
<div id="footnotes"><p class="footnote" data-id="footnote1-chapter1">
</p></div>
Both scripts are in separate .js files that are referred to in the header, and I know this might be the problem for the second script, as it was mentioned that:
"You should put the javascript at the end of your body (just before ), or wrap it in a function listening load or DOMContentLoaded event (e.g. using addEventListener). If not, document.getElementById is executed before the element is loaded to the DOM, so it return null. – " in this post change background color of div.
But I do not know how to "wrap it in a function listening load or DOMContentLoaded event".
Can someone please help me?
Thank you for your help in advance!
You could wrap your code in an on load function, but the general consensus seems to suggest putting your scripts at the end of the body tag instead, according to this StackOverflow answer and the YUI team. This accomplishes the same thing as wrapping your code, and might fix your problem if it's related to DOM dependencies.
So I would recommend you put your scripts at the end of your body tag instead of in your head tag, and see if that helps.
As Nathan mentioned, your anchor has the attribute onclick as onclick="showRightPanel();changeColor();"
But your javascript replaces this attribute, see: els[i].onclick = changeColor;
So only changeColor function will be called.
[update]
As in the comments, the accepted answer:
els[i].onclick = function(){showRightPanel();changeColor.apply(this);}

setting onclick in javascript is not working

So I'm writing some function that is working with Facebook's API. I was previously setting the onclick attribute by taking the parent and saying something along the lines of parent.innerHTML += "<a onclick = 'test("+parameter+")'>Previous</a>" and that worked fine. But I wanted to make it safer and more to standard so it is styled as follows:
function myMethod(link){
...
FB.api(link, function(response){
...
if(value != null){
var prev = document.createElement("a");
prev.innerText = "previous";
prev.setAttribute("id", "previous");
//prev.onclick = function(){test(this);}; doesn't work here
document.getElementById("facebook-photos").appendChild(prev);
}
//some other code (loops and stuff) including this
for(...){
var container = document.createElement("div");
container.classList.add("container");
container.classList.add("thing");
container.onclick = function(){test(this);}; // works here
}
//
if(document.getElementById("previous")){
document.getElementById("previous").onclick = function(){test(this);}; //works here
}
}
}
yet for some reason whenever I try and use this, clicking the element does nothing. Inspecting the element shows no "onclick" field but displaying the element in the console shows that the onclick field is not null. Nothing is covering the element and I've tried it as a div and as a button. When I try and do document.getElementById("previous") earlier, it still doesn't work. Why does this happen? Is it just the asynchronous nature of Javascript? The assignment in the middle works even though its relatively soon after the creation of the element, but the one at the beginning does not.

Element with hidden css not changing with javascript .show()

I have a dropdown list that I am hiding on initialization since it's not needed unless the client actually selections a specific radiobuttonlist object. I'm presently setting it to false through
dlInterval.Attributes.CssStyle[HtmlTextWriterStyle.Visibility] = "hidden";
However, attempting to change this through javascript on selection, is failing, at present, I have my code set up to execute as such.
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#<%=rblVectorChoices.ClientID%>").click(function() {
var intVectorSelectedIndex = $('#<%=rblVectorChoices.ClientID %> input[type=radio]:checked').val();
$("#<%=dlInterval.ClientID %>").style.visibility="visible";
if (intVectorSelectedIndex == 1) {
$("#<%=dlInterval.ClientID%>").show();
} else {
$("#<%=dlInterval.ClientID%>").hide();
}
});
});
</script>
As you can see I'm currently attempting to change the visibility from hidden, back to visible, yet I am receiving an error in the browser console 'TypeError: Cannot set property 'visibility' of undefined'
This doesn't make much sense to me, as the field should be hidden, and not just null. What is causing this to happen, and what is a good solution for such a thing?
The HTML attribute is not called visibility.
In CSS the corresponding attribute for .show() / .hide() is display.
the code you were looking for is :
dlInterval.Attributes.CssStyle["display"] = "none";
or you can just change the javascript to look like, I personally would think that you should hide the element in javascript if your going to show it in javascript . Instead of setting the display:none; in .Net code that is going to disappear when the page is rendered
just re-write your code like this:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
// hide element initially
$("#<%=dlInterval.ClientID%>").hide();
$("#<%=rblVectorChoices.ClientID%>").click(function() {
// much easier way to check if check box is checked
if ( $("#<%=rblVectorChoices.ClientID input[type=radio]:checked%>").is(":checked)) {
$("#<%=dlInterval.ClientID%>").show();
} else {
$("#<%=dlInterval.ClientID%>").hide();
}
});
});
</script>
also , I strongly , strongly reccomend using classes to select your html elements with javascript or jquery , .Net mangles the id's and you have to write out this weird syntax to get the proper id, uses classes prevents all that
NOTE: if you're going to use this second example then you never need to mess with
dlInterval.Attributes.CssStyle["display"] = "none";
Can you use prop and compare if it's true or false? Also, you cant call $("#<%=dlInterval.ClientID %>").style.visibility="visible"; you have to call it this way:
For those of you reminiscing on the missing .NET inline ID's here's my modified code:
$(document).ready(function () {
$("#<%=rblVectorChoices.ClientID%>").click(function () {
var intVectorSelectedIndex = $('#<%=rblVectorChoices.ClientID%>').prop('checked');
$("#<%=dlInterval.ClientID%>").css('visibility', 'visible');
if (intVectorSelectedIndex == true) {
$("#<%=dlInterval.ClientID%>").show();
} else {
$("#<%=dlInterval.ClientID%>").hide();
}
});

Image Hide in and hide out using event handler

I am working on a web page which contains a list of items and sub items for display. In the Div element, I am setting up the values, image. Using the image show and hide option On click event handler is triggered. This seems to be working fine with IE9, but doesn't work with other browsers (FireFox, Chrome and safari).
<div id="Type_A Medicine" value="H" entity="Type A Medicine" onClick="showHide(this,'MIE_Type_A Medicine')"><img src='<%=request.getContextPath()%>/images/plus.gif'>Type A Medicine</div>
function showHide(ctrl,id)
{
if (ctrl.value == "H")
{
ctrl.value = "S";
ctrl.innerHTML = "<img src='<%=request.getContextPath()%>/images/minus.gif'>" +ctrl.getAttribute("entity");
showBlock(id);
}
else if (ctrl.value == "S")
{
ctrl.value = "H";
ctrl.innerHTML = "<img src='<%=request.getContextPath()%>/images/plus.gif'>" + ctrl.getAttribute("entity");
hideBlock(id);
}
}
function hideBlock(blockId)
{
var str = "document.all." + blockId + ".style.display='none'";
eval(str);
}
function showBlock(blockId)
{
var str = "document.all." + blockId + ".style.display=''";
eval(str);
}
I still couldn't figure out the difference with the list of browsers. Kindly help...
I'm guessing it is because you use an invalid ID syntax. ID's cannot have spaces. If you use invalid HTML you can't expect javascript to work the same way across browsers.
id="Type_A Medicine"
Also, you never post the code for showBlock or hideBlock where you pass the ID in. Can't tell what goes wrong there without code.
To retrieve non-standard attributes, you should use .getAttribute() rather than trying to access them as properties.
So ctrl.entity should be ctrl.getAttribute("entity") and the same for other non-standard attributes. Run this example in Chrome: http://jsfiddle.net/jfriend00/Lxna7/.
Also, you should remove the space from your ID value as that's not a legal character and makes the id unusable in many circumstances (where a space is a delimiter between identifiers).
Try closing correctly the image tags to see if that fix the problem:
<img src="path/file.html" />

Categories