Onclick event is not working on first click - javascript

When the page loads I need to click the button twice to trigger the onclick() function. After doing so, everything works as expected.
As I am new to this web development field I would highly appreciate the detailed explanation.
Thank you in advance.
var hamburger = function() {
var menu = document.getElementById('menuBarSlide');
if (menu.style.right == "-300px") {
menu.style.right = "0px";
} else {
menu.style.right = "-300px";
}
}
<div class="navMenuItem hamburger" onclick="hamburger()">
<span class="ham-icon"></span>
<span class="ham-icon"></span>
<span class="ham-icon"></span>
</div>

I suppose that menuBarSlide is the id of a div, if so this should work for you.
I've added some styling to highlight the div, and a console.log() to be sure that the code executes.
Edit: Maybe the problem is that you expect the element to have a value in the right property but it is different, so logging the style can be helpful.
Edit 2: The problem is in the initial value (that is why your first click is not working, so with this variation menu.style.right = menu.style.right || "-100px"; that problem is solved. That line of code assigns -100px if the value comes null. Additionally, the program logs the value before and after the conditional assignment.
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<title>menuBarSlide</title>
<style>
#menuBarSlide { /*To highligth your div*/
position: absolute;
background-color: grey;
color: red;
}
</style>
</head>
<body>
<div class="navMenuItem hamburger" onclick="hamburger()">
<span class="ham-icon">Item1</span>
<span class="ham-icon">Item2</span>
<span class="ham-icon">Item3</span>
</div>
<div id="menuBarSlide">
<h1>menuBarSlide</h1>
</div>
<script>
var hamburger = function() {
var menu = document.getElementById('menuBarSlide');
console.log("before assing: " + menu.style.right); // To check the current style of the element
menu.style.right = menu.style.right || "-100px"; // Assign -100px if is null, otherwise keep the same value
console.log("after assing: " + menu.style.right); // To check the style after the asigment
if (menu.style.right == "-100px") {
menu.style.right = "30px";
}
else {
menu.style.right = "-100px";
}
}
</script>
<body>
<html>

Related

JS onClick event ignores first click, works for every subsequent click

Having a very weird issue with a simple div visibility toggle script.
I'm just using javascript to switch a div between 'display: block' and 'display: none' to toggle its visibility. Very routine stuff.
And in general it works, but it always fails on the first click after a fresh page load. Then it works consistently from the second click onward.
No error output on console.
Relevant HTML:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="res/classes.js"></script>
<script type="text/javascript" src="res/util_c.js"></script>
<script type="text/javascript">
// load client prefs
var clientPrefs = new ClientPrefs();
</script>
</head>
<body>
<a id="join_show_publist" class="a_btn" onClick="javascript:joinPublistToggle()">View Public Matches</a><br />
<!-- list of public games -->
<div id="join_publist_container" class="ovr">
<table id="join_publist_listbox">
<tr id="join_publist_listbox_header">
<td>Table Name</td>
<td>Open</td> <!-- open seats remaining at table -->
</tr>
</table>
<div class="spacer"></div>
<div id="join_savePref_container">
<input id="join_savePref" type=checkbox onclick="javascript:clientPrefs.joinAlwaysShowPubToggle()" />
<span id="join_savePref_label" onclick="javascript:clientPrefs.joinAlwaysShowPubToggle()">Always show public tables list</span>
</div>
</div>
Relevant CSS:
div.ovr {
display: none;
}
...and finally in util_c.js:
// toggle visibility of public tables list
function joinPublistToggle() {
var listContainer = document.getElementById('join_publist_container');
if (listContainer.style.display == 'none') {
listContainer.style.display = 'block';
} else {
listContainer.style.display = 'none';
}
}
First click: nothing happens.
Second click: the DIV is shown
Third click: the DIV is re-hidden
etc..
If I put an alert(listContainer.style.display) into the joinPublistToggle function, the alert comes up empty with the first click, then shows 'none' with the second click.
But the CSS specifically sets the display style for that div as 'none' on load. And if I look at that div in the page inspector after a fresh page load the inspector specifically says the div's display property is set to none.
So the issue seems to be that javascript is reading that property as empty even though that property is set as 'none'.
Why would it do that?
style returns the inline style of the element, and your element doesn't have any, which is why listContainer.style.display returns an empty string and the condition fails.
It would work if you compared against 'block' instead but it's not really more reliable.
function joinPublistToggle() {
var listContainer = document.getElementById('join_publist_container');
if (listContainer.style.display == 'block') {
listContainer.style.display = 'none';
} else {
listContainer.style.display = 'block';
}
}
https://stackoverflow.com/questions/69213611/js-onclick-event-ignores-first-click-works-for-every-subsequent-click/69224191#
The other answers provide valid solutions, here is another using classes:
CSS:
div.hidden {
display: none;
}
HTML:
<div id="join_publist_container" class="ovr hidden">
(of course you can also just keep using ovr but I wasn't sure what that's for)
JS:
function joinPublistToggle() {
document.getElementById('join_publist_container').classList.toggle('hidden');
}
And in general it works, but it always fails on the first click after a fresh page load. Then it works consistently from the second click onward.
I am going to asume when you clicked the link, the checkbox and the table should go away. And when it is clicked again, the table and the checkbox should show. I modified your code and it works for me.
for your HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="classes.js"></script>
<script type="text/javascript" src="util_c.js"></script>
<script type="text/javascript">
// load client prefs
var clientPrefs = new ClientPrefs();
</script>
</head>
<body>
<a id="join_show_publist" class="a_btn" onClick="javascript:joinPublistToggle()">View Public Matches</a><br />
<!-- list of public games -->
<div id="join_publist_container" class="ovr">
<table id="join_publist_listbox">
<tr id="join_publist_listbox_header">
<td>Table Name</td>
<td>Open</td> <!-- open seats remaining at table -->
<td>Starts</td> <!-- time left until game starts (or "started" if underway) -->
<td>Timer</td> <!-- time limit for turns (or "none") -->
<td>Min</td> <!-- min players to start the round (or '--' if already underway) -->
<td>Late</td> <!-- whether late joiners are allowed at the table -->
<td>AI</td> <!-- whether there are any AI players at the table (and if so, how many)
also colour denotes difficulty: green-easy / yellow-med / red-hard -->
</tr>
<!-- Generate list via js. Clicking any list entry joins -->
</table>
<div class="spacer"></div>
<div id="join_savePref_container">
<input id="join_savePref" type=checkbox onclick="javascript:clientPrefs.joinAlwaysShowPubToggle()" />
<span id="join_savePref_label" onclick="javascript:clientPrefs.joinAlwaysShowPubToggle()">Always show public tables list</span>
</div>
</div>
Classes.js:
// ClientPrefs - client-side preferences
class ClientPrefs {
constructor() {
// JOIN GAME page settings
this.joinAlwaysShowPub = false;
}
joinAlwaysShowPub() { return joinAlwaysShowPub; }
joinAlwaysShowPubToggle() {
// toggle setting in memory
this.joinAlwaysShowPub = !this.joinAlwaysShowPub;
// update checkbox & label
document.getElementById('join_savePref').checked = this.joinAlwaysShowPub;
}
}
And finally your other script:
function joinPublistToggle() {
var listContainer = document.getElementById('join_publist_container');
if (listContainer.style.display == 'none') {
listContainer.style.display = 'block';
} else {
listContainer.style.display = 'none';
}
}
Here are few reasons why your code might not work:
I think the problem is that you mistyped joinPublistToggle() to joinShowPubList.
Your div has a value of nothing for the display property. So, when JS looks at your div, well, the div is not set to none or block, I don't know how to handle it. After you clicked the link a second time, it sets the display in your JS code. So, it knows how to handle it.
Maybe add an display property to your a tag and set it to block so JS know what the property of the style is.
<a id="join_show_publist" class="a_btn" onClick="javascript:joinPublistToggle()" style="display:block;">View Public Matches</a><br />
This doesn't really answer my question, but I've implemented a simple workaround by adding an OR statement into the JS function:
function joinPublistToggle() {
var listContainer = document.getElementById('join_publist_container');
if ( (listContainer.style.display == 'none') ||
(listContainer.style.display == '' ) ) {
listContainer.style.display = 'block';
} else {
listContainer.style.display = 'none';
}
}
This doesn't explain why it was behaving so odd, and it isn't a proper solution (as a proper solution would address the cause, not the symptom).
But it works.
I won't mark the post as solved just yet in case any wizards end up reading this and are able to explain why the problem occurred in the first place.

javascript - one image,two actions

I am looking for javascript command that would do the following:
Click on image -> open spoiler
Click on image again -> hide spoiler
Here is what I got so far:
javascript in my html
<script>
function myFunction() {
document.getElementById("prvy").innerHTML = document.getElementById('spoiler_id').style.display='';}
</script>
Spoiler
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
And my button:
<div id="prvy" onclick="myFunction()"></div>
What I managed to do, is to click on a image, wich will open spoiler. Hovewer, I've been unable to do the second part, onclick again it will close the spoiler.
I also did serach for solution alredy, nothing worked for me, not even this: Link
I also tired if{} else{} statement but didn't work for me either.
Help would be really appreciated, as I am getting desperate on this one.
You can use jQuery .toggle() to toggle show/hide
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
Note : You need to include jQuery in your document as
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Working snippet :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
<div id="prvy" onclick="myFunction()">button</div>
<script>
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
</script>
In the JavaScript where you click the button use the simple jQuery function toggle.
$('#spoiler_id').toggle();
Toggle will hide the element selected if it is currently shown or display the element if it is currently hidden.
you would need some state that flips when the function is called.
like this.
<script>
var state = false;
function myFunction() {
state = !state;
if(state){
//do something
}else{
//do something else
}
}
</script>
Is that all of your code, it would be easier for you and less confusing too if you just gave the buttons an on click function and then called that function in your js.
Can I see all of your html
I am giving an example to concerned question using javascript.
HTML:
<script type="text/javascript">
var permit = 'true';
function showhide() {
var getcont = document.getElementsByClassName('hidshowcont');
if (permit === 'true') {
permit = 'false';
getcont[0].style.display = 'block';
}
else {
permit = 'true';
getcont[0].style.display = 'none';
}
}
</script>
<style type="text/css">
.hidshowcont{
height: 200px;
width: 300px;
border: 1px solid #333333;
display: none;
}
</style>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR1cSDTn18ufwjuMihttTvCPJOnFY-4hxbPcaOVd87nSPaQakbP9IERaQ" />
<br />
<br />
<div class="hidshowcont">
This is an example of hide and show the container by clicking of an image.
</div>
This will help u much

What is the best way to implement previous and next page logic

I have a webpage which is a huge form (6 pages long). In order to make it more user friendly, I decided to break this down into different sections (div tags).
I have placed Previous and Next button on page. On previous click it should display the previous div tag I was at and next should display the next div tag. I was wondering what would be the best way to implement it? So far I have this function which I know is hardcoded for div tag called GeneralSection. Just like GeneralSection, I have 20 more sections. Any ideas how should I go about it ? Help appreciated! :)
$(document).ready(function () {
$("#imgNext").click(function () {
$("#GeneralSection").hide();
});
});
You could just iterate through an array of elements.
Here's a simple JSBin that should get you going: https://jsbin.com/siyutumizo/edit?html,js,output
$(document).ready(function() {
var $steps = $('.step');
var currentStep = 0,
nextStep;
$steps.slice(1).hide(); //hide all but first
$('#next').on('click', function(e) {
e.preventDefault();
nextStep = currentStep + 1;
if (nextStep == $steps.length) {
alert("You reached the end");
return;
}
$($steps.get(currentStep)).hide();
$($steps.get(nextStep)).show();
currentStep = nextStep;
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="wizard">
<div class="step">1</div>
<div class="step">2</div>
<div class="step">3</div>
<div class="step">4</div>
<div class="step">5</div>
<div class="step">6</div>
</div>
<button id="next">Next</button>
</body>
</html>
Another way of implementing this is through siblings.
Jsbin: https://jsbin.com/tarajuyusu/edit?html,js,output
$(function() {
$('div#GeneralSection').slice(1).hide(); // hide all section, except for first one
$('#imgNext').on('click', function() {
var section = $('div#GeneralSection').filter(':visible');
if ($(section[0].nextElementSibling).attr('id') != "GeneralSection")
return;
section.hide();
$(section[0].nextElementSibling).show();
});
$('#imgPrev').on('click', function() {
var section = $('div#GeneralSection').filter(':visible');
if ($(section[0].previousElementSibling).attr('id') != "GeneralSection")
return;
section.hide();
$(section[0].previousElementSibling).show();
});
});
Give each section class pages and per section ids page-1, page-2 like that
$(document).ready(function () {
var pages = $(".pages").length;
$("#imgNext").click(function () {
var nextPageNo = parseInt($(".pages:visible")[0].id.split('-')[1])+1;
if(nextPageNo > pages)
return false;
$(".pages:visible").fadeout();
$("#page-"+nextPageNo).fadeIn();
});
});
Havent fully tetsted but this should get you going.
Update
HTML
<div id="container">
<div id="page-1" class="pages">1</div>
<div id="page-2" class="pages">2</div>
<div id="page-3" class="pages">3</div>
<div id="page-4" class="pages">4</div>
<div id="page-5" class="pages">5</div>
<div id="page-6" class="pages">6</div>
</div>
CSS
.pages{
display: none;
}
#page-1{
display: block;
}

How do I reverse this JavaScript code?

I have a webpage that has a link set to change the background colour of the page, the colour of the link, & the link text. Here is my code:
<html>
<head>
<title>Title</title>
<script type="text/javascript">
function Lights() {
document.body.style.backgroundColor='#000000';
document.getElementById("on").innerHTML="Turn on the lights";
document.getElementById("on").style.color="#00ffff";
}
</script>
</head>
<body style="font-size:200px; text-align:center;">
Turn off the lights
</body>
</html>
I was wondering how I would set the JavaScript to reverse those statements when the link is clicked again so the page is back to the white background, the text is back to "Turn off the lights", & the link is back to the darker blue.
Thank you
You can use a variable to store the state and toggle based off that.
<script type="text/javascript">
var toggle = false;
function Lights() {
var link = document.getElementById("on");
document.body.style.backgroundColor= toggle ? '#ffffff' : '#000000';
link.innerHTML=toggle ? "Turn off the lights": "Turn on the lights";
link.style.color= toggle ? '#000000': "#00ffff";
toggle = !toggle;
}
</script>
You can toggle the settings based on a class value:
<a ... class="lightsOn" onclick="Lights(this);" ...>Turn off the lights</a>
then:
function lights(element) {
if (element.className == 'lightsOn') {
element.className = 'lightsOff';
// do settings for lights off
} else {
element.className = 'lightsOn';
// do settings for lights on
}
}
Most of the setting can be assigned to the class in CSS rather than hard coded in the function.
Note that function names starting with a capital letter are, by convention, reserved for constructors, and you shouldn't use an A element if you don't want an A, use a span with appropriate styling:
<style type="text/css">
.clickable {
cursor: pointer;
text-decoration: underline;
font-color: blue;
}
</style>
<span class="clickable" ...> ... </span>

javascript highlight

i try to make the div color changed when click or focus on textbox so i do this js function but it change the textbox color not its div
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<style type="text/css">
/* This is the CSS class to use when no focus is on the input control */
.input_text
{
border:1px solid #c0c0c0;
padding:4px;
font-size:14px;
color:#000000;
background-color:#ffffff;
}
/* This is the CSS class to use when the control has focus */
.input_text:focus, input.input_text_focus
{
border-color:#646464;
background-color:#ffffc0;
}
</style>
<script type="text/javascript">
// creates a function to set the css class name of input controls when they
// receive or lose focus.
setAspnetTextFocus = function() {
// CSS class name to use when no focus is on the input control
var classBlur = 'input_text';
// CSS class name to use when the input control has focus
var classFocus = 'input_text_focus';
// get all of the input tags on the page
var inputElements = document.getElementsByTagName('input');
for (var i = 0; i < inputElements.length; i++) {
inputElements[i].onfocus = function() {
if (this.className == 'input_text') {
this.className += ' ' + classFocus;
}
}
// add the onblur event and set it to remove the on focused CSS class when it loses focus
inputElements[i].onblur = function() {
this.className = this.className.replace(new RegExp(' ' + classFocus + '\\b'), '');
}
}
}
// attach this event on load of the page
if (window.attachEvent) window.attachEvent('onload', setAspnetTextFocus);
</script>
</head>
<body>
<div class="input_text" >
<input type="text" id="TextBox1" class="input_text" />
</div>
</body>
</html>
any ideas?
To change the text select color you just need CSS. You wont be able to do it with JavaScript except with not so pretty hacks (you'd need to draw a rectangle on top/below the words on select...)
With CSS tho you just need to do (i believe):
#TextBox1::selection {
background: #ffb7b7; /* Safari */
}
#TextBox1::-moz-selection {
background: #ffb7b7; /* Firefox */
}
Source: http://css-tricks.com/overriding-the-default-text-selection-color-with-css/
Just a side note tho in case you care, this is NOT W3C validated CSS.
here is a jsfiddle using JQuery that will do what I think you are asking for: http://jsfiddle.net/pthurlow/GG6Te/
here it is in plain vanilla JS: http://jsfiddle.net/FSZZU/
EDIT code from jsfiddle:
html
<div class="input_text">
<input type="text" id="TextBox1" class="input_text" />
</div>
script
document.getElementById('TextBox1').onfocus = function() {
this.parentNode.className = 'input_text focus_text';
};
document.getElementById('TextBox1').onblur = function() {
this.parentNode.className = 'input_text';
};

Categories