I have a javascript function that is supposed to make visible objects hidden and hidden objects visible. since I lack of basic javascript knowlegde, I came here to ask help from you :/ Can someone help me out with my code so that I can learn a little?
function DisplayMenu(obj) {
if (obj.style.visibility == 'visible') {
obj = document.getElementById(obj);
obj.style.visibility = 'hidden';
}
else if (obj.style.visibility == 'hidden') {
obj = document.getElementById(obj);
obj.style.visibility = 'visible';
}
}
You need to define what obj is before the if:
function DisplayMenu(obj) {
var obj = document.getElementById(obj);
if (obj.style.visibility == 'visible') {
obj.style.visibility = 'hidden';
}
else {
obj.style.visibility = 'visible';
}
}
EDIT: You could simplify it, you don't need the else if just use else
And even shorter version which checks for existance of obj_id before assignment, so in the case there is no obj_id in DOM it doesn't trigger exception:
function DisplayMenu(obj_id) {
var obj = document.getElementById(obj_id);
obj && obj.style.visibility = (obj.style.visibility == 'visible') ? 'hidden' : 'visible';
}
Related
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;
}
}
});
i want to toggle two menus offered by two buttons.the issue is when i click on button one, it shows the menu bound with button one but when i click the other, it shows both instead of hiding the first one and vice versa, on my login page. The menus are identified by the ids of; 'reqpwd' and 'signup' in html / JS. What is worng? also suggest improvement in code if possible. My JS code:
<script>
window.onload = function() {
document.getElementById('reqpwd').style.display = 'none';
document.getElementById('signup').style.display = 'none';
};
function chk(elm) {
var signup_ = signup.id;
var reqpwd_ = reqpwd.id;
elm_ = elm.id;
if (elm_ == reqpwd_){
hide(signup_);
show(reqpwd_);
}
if (elm_== signup_){
hide(reqpwd_);
show(signup_);
}
};
function show(abc) {
var menuBox = document.getElementById(abc);
if(menuBox.style.display == "none") { // if is menuBox displayed, hide it
menuBox.style.display = "block";
} };
function hide(abc){ // if is menuBox hidden, display it
var menuBox = document.getElementById(abc);
if(menuBox.style.display == "block"){
menuBox.style.display == "none";
}
};
</script>
Instead of menuBox.style.display == "none"; try using menuBox.style.visibility== "hidden";
Edit:
I have changed a few things in your code. Didn't make a whole lot of sense to me the way you're setting the styles on load (missing HTML), so I had to use IDs that made sense to me.
Edit:
Ok, my bad. I updated the code. I think the problem is on hide you're using double equals instead of single equals on menuBox.style.display == "none";. Thus the menu is never hiding.
https://codepen.io/juanferrer/pen/qmOmWa
Finally i have landed into something like this using the flag variable as a state indicator.. now the only requirement is to check toggle as well as disappear the relevant menu by the same button..i.e. if signup menu is already open, the signup or reset button should close it and vice versa.
window.onload = function() {
document.getElementById('regd').style.visibility = 'hidden'; //regisration msg
document.getElementById('rset').style.visibility = 'hidden'; //reset msg
document.getElementById('reqpwd').style.display = 'none';
document.getElementById('signup').style.display = 'none';
};
var flag = 0;
function chk(elm) {
var signup_ = signup.id;
var reqpwd_ = reqpwd.id;
elm_ = elm.id;
if (elm_ == reqpwd_ && flag === 0 || elm_ == reqpwd_ && flag == 2) {
flag = 1;
hide(signup_);
show(reqpwd_);
}
if (elm_ == signup_ && flag === 0 || elm_ == signup_ && flag == 1) {
flag = 2;
show(signup_);
hide(reqpwd_);
}
if (elm_ == reqpwd_ && flag == 1 || elm_ == signup_ && flag == 2) {
hide(elm_);
flag = 0;
}
};
function show(abc) {
var menuBox = document.getElementById(abc);
if (menuBox.style.display === "none") { // if is menuBox hidden, display it
menuBox.style.display = "block";
}
};
function hide(abc) { // if is menuBox
var menuBox = document.getElementById(abc);
if (menuBox.style.display === "block") { //if displayed, hide it
menuBox.style.display = "none";
}
};
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
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');
}
}
}
Test if the image I am about to grab using code is visible to the user or not
Limitations:
Plain javascript - please do not suggest jQuery or other framework
I am only interested in display:none and visibility:hidden but opacity and such is of course welcome
Code: below (taken from here) does not work in my DEMO
Question: Can you help making either work or suggest a better script?
Version A
function isVisible(obj){
if (obj == document) return true;
if (!obj) return false;
if (!obj.parentNode) return false;
if (obj.style) {
if (obj.style.display == 'none' || obj.style.visibility == 'hidden') return false;
}
else if (window.getComputedStyle) { // MY BAD - I PUT THE INCORRECT ELSE HERE
var style = window.getComputedStyle(obj, "");
if (style.display == 'none' || style.visibility == 'hidden') return false;
}
else if (obj.currentStyle) {
var style = obj.currentStyle;
if (style['display'] == 'none' || style['visibility'] == 'hidden') return false;
}
return isVisible(obj.parentNode);
}
Version B
function isVisible1(obj) {
var cnode = obj;
try {
while(cnode) {
if (cnode.nodeName) {
if (cnode.nodeName.toLowerCase()=="body") {
return true;
}
}
if (cnode.style.display=="none" || cnode.style.visibility=="hidden") {
return false;
}
cnode = cnode.parentNode;
}
return true;
}
catch(ex) {return false;}
}
Try taking the computed style conditionals outside the else of the style check. We want to check both the inline styles and the computed styles (from stylesheets.)
Changing:
else if (window.getComputedStyle) {
To:
if (window.getComputedStyle) {
Forked fiddle: http://jsfiddle.net/MXgbh/1/