onclick javascript function does not work in IE - javascript

var myButton = document.getElementsByTagName("input");
myButton[0].onclick = function() {
if(ansArray[0] == 'a')
myButton[0].style.backgroundColor = "green";
else
myButton[0].style.backgroundColor = "red";
}
myButton[1].onclick = function() {
if(ansArray[0] == 'b')
myButton[1].style.backgroundColor = "green";
else
myButton[1].style.backgroundColor = "red";
}
onclick function not working in my above example(IE9), but they work fine in Chrome and Firefox.

The issue is that your DOM is not yet loaded when you are trying to access the buttons. Wrap your onclick handlers in window.load and everything should work fine:
window.onload = function () {
var myButton = document.getElementsByTagName("input");
myButton[0].onclick = function() {
if(ansArray[0] == 'a') {
myButton[0].style.backgroundColor = "green";
} else {
myButton[0].style.backgroundColor = "red";
}
}
myButton[1].onclick = function() {
if(ansArray[0] == 'b') {
myButton[1].style.backgroundColor = "green";
} else {
myButton[1].style.backgroundColor = "red";
}
}
}
I am actually surprised this works under Webkit and Mozilla. I have created a small demo fiddle. In all cases, in all browsers the object comes out as null before load, unless the script block is after the element you are accessing inside the body.
Notice though that there is a difference in how getElementsByTagName reacts inside different browsers, it is different than getElementById: fiddle
Another alternative would be to not wait for window.onload would be to wait for document.body because window.onload happens after all content including images is loaded.
function Start() {
if (document.body) {
var myButton = document.getElementsByTagName("input");
myButton[0].onclick = function() {
if(ansArray[0] == 'a') {
myButton[0].style.backgroundColor = "green";
} else {
myButton[0].style.backgroundColor = "red";
}
}
myButton[1].onclick = function() {
if(ansArray[0] == 'b') {
myButton[1].style.backgroundColor = "green";
} else {
myButton[1].style.backgroundColor = "red";
}
}
}
}
setInterval(Start, 50); // 50 ms is a small enough interval to retry

Same answer I used here Javascript onclick functions do not work should apply.

Related

how do I hide an element in javascript if localstorage variable is true

I'm trying to hide a video when the page loads and keep the video shown after any link is pressed
this is my current code
var videoplayer = document.getElementById("videoplayerlayer");
var links = document.getElementsByTagName("a");
if(localStorage !== 'undefined')
{
console.log("localStorage exists")
if(localStorage["vv"] == false)
{
videoplayer.style.display = "none";
localStorage["vv"] = false;
}
else
{
for( i=0; i<links.length; i++ )
{
links[i].onclick = function()
{
localStorage["vv"] = true;
videoplayer.style.display = "block";
console.log(localStorage["vv"]);
}
}
}
}
else
{
localStorage["vv"] == false;
}
localStorage only holds strings. localStorage["vv"] = false; stores the string "false", which is not falsy.
Normally I store JSON and parse it. That's probably overkill here, though, just store "Y" or "N" as the flag and check that:
var videoplayer = document.getElementById("videoplayerlayer");
var links = document.getElementsByTagName("a");
if (typeof localStorage !== 'undefined')
// ^^^^^^ Note 2
{
console.log("localStorage exists")
if(localStorage["vv"] == "N")
{
videoplayer.style.display = "none";
// No need, it's already stored - localStorage["vv"] = false;
}
else
{
for( var i=0; i<links.length; i++ )
// ^^^^---- Note 1
{
links[i].onclick = function()
{
localStorage["vv"] = "Y";
videoplayer.style.display = "block";
}
}
}
}
/* You don't want this, it'll throw an error, since we know `localStorage` is falsy
else
{
localStorage["vv"] == false;
}
*/
However, nothing in the logic reasonably sets localStorage["vv"] to "N" (the one assignment that was there was in a branch where it's already there). You'll need to add something to set it, unless you want to default to hiding the video player and only show it when localStorage["vv"] is "Y" (or if local storage isn't accessible).
For instance, this hides the player and only shows it if the flag is "Y" on load or one of those links is clicked:
var videoplayer = document.getElementById("videoplayerlayer");
var links = document.getElementsByTagName("a");
if (typeof localStorage !== "undefined") {
if (localStorage.vv !== "Y") {
videoplayer.style.display = "none";
}
for (var i = 0; i < links.length; i++)
{
links[i].onclick = function()
{
localStorage["vv"] = "Y";
videoplayer.style.display = "block";
};
}
}
Note 1: Your code was falling prey to The Horror of Implicit Globals (that's a post on my anemic little blog). Be sure to declare your variables. See the "Note" comment above.
Note 2: Your check for whether you can use local storage was incorrect. I've updated it to what you probably meant above, but see see here for more thorough checks you'll want to use.
Note 3: I would recommend using modern event handling rather than setting onclick.
Below code can help you
$get('<%= AnchorId.ClientID %>').click(function(){
if(localStorage !== 'undefined'){
if(localStorage == false)
{
$get('<%= videoplayerlayer.ClientID %>').hide();
localStorage["vv"] = false;
}
else
{
$get('<%= videoplayerlayer.ClientID %>').show()
localStorage["vv"] = true;
}
}
});

Error in javascript

I am trying to get a collapsible link list to work using JavaScript.
However, there is a continual error in the Java document and I don't know why:
var css Node = document.createElement('link');
cssNode.setAttribute('rel', 'stylesheet');
cssNode.setAttribute('type', 'text/css');
cssNode.setAttribute('href', 'javascript-overrides.css');
document.getElementsByTagName('head')[0].appendChild(cssnode);
function toggle(toggler) {
if (document.getElementById) {
targetElement = toggler.nextsibling;
if (targetElement.classname == undefined) {
targetElement = toggler.nextsiblig.nextsibling;
}
if {
targetElement.style.display == "block") {
targetElement.style.display = "none";
}
else {
targetElement.style.display = "block"
}
}
}
function swap(targetid) {
if (document.getElementById) {
target = document.getElementById(targetid);
if (target.style.display == "block") {
target.style.display = "none";
}
else {
target.style.display = "block";
}
}
}
The error in on line 15 where is states "if ( document.getElementById){" but it seems fine to me.
Any advice?
jsLint returns 3 errors (and assuming your first line is var cssNode)
Compare to undefined with === ( if (targetElement.classname === undefined) )
if { targetElement.style.display == "block")} must be if (
Missing semicolon (targetElement.style.display = "block")
Broken Fiddle here (Push the jsLint button to see the errors)
Fixed Fiddle here

Javascript - Display div

I need to check onload if an anchor is within the URL to open a tab if required. The problem is that if a user opens a tab before the onload function gets fired, the tab gets closed and the user needs to open it again.
How to fix that?
HTML:
<body onload="checkurl()">
JS:
function checkurl(){
if (window.location.hash == '#about')
{
showhide('secabout');
}
else if (window.location.hash == '#contact')
{
showhide('seccontact');
}
}
JS function:
var divState = {};
function showhide(id) {
if (document.getElementById) {
var divid = document.getElementById(id);
divState[id] = (divState[id]) ? false : true;
for (var div in divState){
if (divState[div] && div != id){
document.getElementById(div).style.display = 'none';
divState[div] = false;
}
}
divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
}
}
Thanks.
Uli
I'm pretty sure that <script> tags inside of <head> execute right away before onload() so try that.
You can call the function with an extra parameter to make sure will show in your load function.
Then check on a global initialized variable to check if the function has already been executed by user when running from the checkurl function. This is required if the user clicks on a different tab than the one specified in the URL.
Also you need to check on divState[id] instead of divid.style.display == 'block' when updating divid.style.display at bottom.
function checkurl(){
if (window.location.hash == '#about')
{
showhide('secabout', true);
}
else if (window.location.hash == '#contact')
{
showhide('seccontact', true);
}
}
var divState = {};
var initialized = false;
function showhide(id, initialize) {
if(initialized && initialize) return;
initialized = true;
if (document.getElementById) {
var divid = document.getElementById(id);
divState[id] = (divState[id]) ? false : true;
for (var div in divState){
if (divState[div] && div != id){
document.getElementById(div).style.display = 'none';
divState[div] = false;
}
}
if(initialize){
divid.style.display = 'block';
} else {
divid.style.display = (divState[id] ? 'block' : 'none');
}
}
}

Javascript - Toggle Element only works one way! Also help required for URL append

I am trying to use a toggle script to show and hide certain elements of a page... it works fine hiding the Table containing a list of links and showing the Table with the content inside, but using it to reverse this does not work at all!
<script type="text/javascript">
function getElement(iElementId)
{
if (document.all)
{
return document.all[iElementId];
}
if (document.getElementById)
{
return document.getElementById(iElementId);
}
}
function toggleElement(oElement)
{
if (oElement.style.display == "none")
{
oElement.style.display = "inline";
}
else if (oElement.style.display == "inline")
{
oElement.style.display = "none";
}
else
{
oElement.style.display = "none";
}
}
function OpenPage(name) {
// other function not relevant here //
toggleElement( getElement('MainTable'));
toggleElement( getElement('ContentTable'));
return false;
}
function Switchback(){
// document.getElementById(MainTable).style.display = "inline";
// document.getElementById('ContentTable').style.display = "none";
toggleElement( getElement('MainTable'));
toggleElement( getElement('ContentTable'));
return false;
}
</script>
Even just trying a "getElementByID" function doesn't work for the switching back to displaying the main table of links and hiding the content table... Any way to make it work? thanks.
(also, whilst we're at it, what is the best way to append a URL using Javascript/AJAX? as the page is presently forum/index.php but when a link to a forum is clicked I want the URL to append to forum/index.php?f= and then the relevant number)
<script type="text/javascript">
function getElement(iElementId)
{
if (document.all)
{
return document.all[iElementId];
}
if (document.getElementById)
{
return document.getElementById(iElementId);
}
}
function toggleElement(oElement)
{
if (oElement.style.display == "none")
{
oElement.style.display = "inline";
}
else if (oElement.style.display == "inline")
{
oElement.style.display = "none";
}
else
{
oElement.style.display = "none";
}
}
function OpenPage(name) {
// other function not relevant here //
toggleElement( getElement('MainTable'));
toggleElement( getElement('ContentTable'));
return false;
}
function Switchback(){
// document.getElementById(MainTable).style.display = "inline";
// document.getElementById('ContentTable').style.display = "none";
toggleElement( getElement('MainTable'));
toggleElement( getElement('ContentTable'));
return false;
}
</script>

ajax hidding div problem in IE

I have a javascript page which checks an email and username, this works fine in every browser but Internet Explorer. The div box where errors are shown should be hidden unless an error is given e.g. username taken or invalid email.
If the email gets an error this is shown in the div tag, but doesnt work for username (in all browsers)
below is my code:
<script type="text/javascript">
var usernameok;
var emailok;
function checksubmit()
{
if (usernameok && emailok) {
document.getElementById("button").disabled = false;
} else {
document.getElementById("button").disabled = true;
}
}
function username(username)
{
make_request();
function stateck()
{
if (httpxml.readyState == 4) {
if (httpxml.responseText.indexOf("Username Ok") >= 0) {
usernameok = true;
} else {
usernameok = false;
}
checkCanSubmit();
}
}
httpxml.onreadystatechange = stateck;
user_url = "check_username.php?username=" + username.value;
httpxml.open("GET", user_url, true);
httpxml.send(null);
}
function email(email)
{
make_request();
function stateck()
{
if (httpxml.readyState == 4) {
if (httpxml.responseText.indexOf("Email Ok") >= 0) {
emailok = true;
} else {
emailok = false;
}
checkCanSubmit();
}
}
httpxml.onreadystatechange = stateck;
email_url = "check_email.php?email=" + email.value;
httpxml.open("GET", email_url, true);
httpxml.send(null);
}
</script>
I see your function stateck() is the return function from the HTTP request. However, you are defining it within another function. Not as an anonymous function, but just as a function within another function.
I see what you're doing now...ok, try this instead:
httpxml.onreadystatechange = function()
{
if (httpxml.readyState == 4) {
if (httpxml.responseText.indexOf("Email Ok") >= 0) {
document.getElementById("email").style.backgroundColor = "green";
document.getElementById("email").style.color = "white";
document.getElementById("email_div").style.display = 'none';
emailok = true;
} else {
document.getElementById("email").style.backgroundColor = "red";
document.getElementById("email_div").innerHTML=httpxml.responseText;
emailok = false;
}
checkCanSubmit();
}
};
Do you need to set your initial state to display: none? I think IE may initialize the divs with a non-0 height whereas the divs may be technically visible in other browsers but too short to see.
Edit:
Okay I think I misunderstood your question. Your problem is not with hiding the divs but with displaying errors for the username.
Nothing obvious jumps out at me. Try stepping through the code using VS or VWDE:
http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/

Categories