Javascript if and else runs simultaneously - javascript

I want a link to select by onclick, when the link is clicked so selected, the background should change. When I click the selected link again then the background should be transparent again.
My Script:
<div style="background: transparent;" onclick="click()" id="0">
HTML:
Click
function click() {
var click = document.getElementById("0");
if(click.style.background == "transparent") {
click.style.background = "red";
}
else {
click.style.background = "transparent";
}
}

As far as I understand, you simply want a toggle. Functional code as follows.
2 important notes:
ID must not be zero (or it breaks): I replaced it by 10;
don't use click() as it's a reserved name: I replaced it by toggle().
Not much change to your code apart from the above.
Cheers.
Update to handle multiple divs: I now pass the object:
<html>
<body>
<div style="background: red;" onclick="toggle(this)" id="10">
CLICK ON 10 TO TOGGLE MY BACKGROUND COLOR
</div>
<div style="background: red;" onclick="toggle(this)" id="20">
CLICK ON 20 TO TOGGLE MY BACKGROUND COLOR
</div>
<script>
function toggle(o) {
if(o.style.background == "transparent") {
o.style.background = "red";
alert("red on "+o.id);
}
else {
o.style.background = "transparent";
alert("transparent on "+o.id);
}
}
</script>
</body>
</html>

Two things here, don't call the function click, and use the backgroundColor property, not background as background is a compound property expecting more values than just the color, so comparing it to just a color (i.e. = 'transparent") may not work
so
HTML:
<div style="background-color: transparent;" onclick="notclick()" id="0">
Javascript
function notclick() {
var click = document.getElementById("0");
if(click.style.backgroundColor == "transparent") {
click.style.backgroundColor = "red";
}
else {
click.style.backgroundColor = "transparent";
}
}
EDIT
to handle mutliple div
every div that you want the behaviour, should be like this (i.e. with the onclick(this))
<div style="background-color: transparent;" onclick="notclick(this)" id="0">
<div style="background-color: transparent;" onclick="notclick(this)" id="1">
<div style="background-color: transparent;" onclick="notclick(this)" id="2">
and the javascript should be
function notclick(ele) {
if(ele.style.backgroundColor == "transparent") {
ele.style.backgroundColor = "red";
}
else {
ele.style.backgroundColor = "transparent";
}
}
or better still
function notclick(ele) {
ele.style.backgroundColor = (ele.style.backgroundColor == "transparent" ? "red" :"transparent");
}

The problem is the method name click, inside the onclick handler it refers to the internal click method - fiddle - here click is a native method, not our method
Rename it and it should be fine - you need to use backgroundColor
<button onclick="testme()">Test</button>
then
function testme() {
var click = document.getElementById("0");
if (click.style.background == "red") {
click.style.background = "transparent";
} else {
click.style.background = "red";
}
}
Demo: Fiddle

Related

Div Hide And Show

In the picture, all the prices are in EUR, the prices of tr are hidden on the site.
When I click on the link above, TL and TL prices will be shown and euro prices will be hidden.
When I click on the euro link, the tl will be hidden and the euro will be displayed.
There is a problem in the code but I couldn't solve it
thanks in advance
<button onclick="TL()">TL</button>-<button onclick="EURO()">EURO</button>
<div id="fiyat"> 29.5 </div><div id="fiyattl" style="display: none;" > 400 TL </div>
<div id="fiyat1"> 29.5 </div><div id="fiyattl1" style="display: none;" > 500TL</div>
<div id="fiyat2"> 29.5 </div><div id="fiyattl2" style="display: none;" > 600TL </div>
<div id="fiyat3"> 29.5 </div><div id="fiyattl3" style="display: none;" > 700 TL</div>
<div id="fiyat4"> 29.5 </div><div id="fiyattl4" style="display: none;" > 800 TL</div>
<script>
function TL() {
var x = document.getElementById("fiyattl");
var y = document.getElementById("fiyattl1");
var z= document.getElementById("fiyattl2");
var t = document.getElementById("fiyattl3");
var w = document.getElementById("fiyattl4");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
if (y.style.display === "none") {
y.style.display = "block";
} else {
y.style.display = "none";
}
if (z.style.display === "none") {
z.style.display = "block";
} else {
z.style.display = "none";
}
if (t.style.display === "none") {
t.style.display = "block";
} else {
t.style.display = "none";
}
if (w.style.display === "none") {
w.style.display = "block";
} else {
w.style.display = "none";
}
}
</script>
If you assign a className to these div elements that reflects the currency then you can identify all the nodes that are to be either hidden or displayed quite easily using native javascript methods. In the following the inline event handlers are replaced with externally registered listeners that use the name of the clicked button to identify the price nodes that have that name as the class attribute. You could use dataset attributes instead of course but there is no need to use multiple IDs which can easily become hard to maintain and prone to troubles.
/*
querySelectorAll will attempt to match DOM elements based upon the
expression used. Here we find both/all buttons in the DOM - this
could be honed to identify ONLY the buttons of interest if required
by modifying the buttons (add a className for instance) and editing the
expression used.
The button collection is iterated through and an event listener is
added to process the `click` event.
*/
document.querySelectorAll('button').forEach(bttn=>bttn.addEventListener('click',function(e){
/*
The click event handler
Identify the DIV elements that have the class attribute that matches the name of the button.
Iterate through that collection and set the display property to "block"
*/
let col=document.querySelectorAll( 'div.'+this.getAttribute('name') );
col.forEach( n => n.style.display='block' )
/*
then identify the DIV elements that are not relevant, iterate through
that collection and assign them as hidden.
*/
col=document.querySelectorAll('div:not([class="'+this.getAttribute('name')+'"])');
col.forEach( n => n.style.display='none' );
}));
<button name='tl'>TL</button>-<button name='euro'>EURO</button>
<div class='euro'>29.5</div><div class='tl' style='display:none;'>400 TL</div>
<div class='euro'>29.5</div><div class='tl' style='display:none;'>500TL</div>
<div class='euro'>29.5</div><div class='tl' style='display:none;'>600TL</div>
<div class='euro'>29.5</div><div class='tl' style='display:none;'>700 TL</div>
<div class='euro'>29.5</div><div class='tl' style='display:none;'>800 TL</div>

Hide and Unhide div with the same button

I am using a code that unhides a hidden div.
HTML:
<div id="unhide" style="display:none;">DUMMY TEXT</div>
<button id="expand" name="expand">Show The Div</button>
JS:
document.getElementById("expand").addEventListener("click", function()
{
document.getElementById('unhide').style.display = "block";
});
How can I make the same button hide the div after clicking it again? Is it possible to alter the code I am using now?
use toggle to simple hide and unhide div
$("#expand").click(function() {
$("#unhide").toggle();
});
Use toggle for this show and shide, see below code.
$(document).ready(function(){
$("#expand").click(function(){
$("#unhide").toggle();
});
});
By doing some modifications in JavaScript, you can use the same button to hide the div as well as you can change the button text like below.
JS:
document.getElementById("expand").addEventListener("click", function()
{
var displayDiv = document.getElementById('unhide');
var displayValue = (displayDiv.style.display === "block") ? "none" : "block";
this.innerHTML = (displayValue === "block") ? "Hide The Div" : "Show The Div";
displayDiv.style.display = displayValue;
});
Link reference: https://jsfiddle.net/pitchiahn/hctnvsz1/1/
use simple if-else control flow
document.getElementById("expand").addEventListener("click", function()
{
var elem = document.getElementById('unhide');
if(elem.style.display == "none") { elem.style.display = "block"; }
else { elem.style.display = "none"; }
});
You can use .toggle()
$('#buttonId').on('click', function(e){
$("#DivId").toggle();
$(this).toggleClass('class1')
});​
.class1
{
color: orange;
}​
use toggleClass() to toggle the class for the button
$('#buttonLogin').on('click', function(e){
$("#login_Box_Div").toggle();
$(this).toggleClass('class1')
});​
.class1
{
color: orange;
}​
document.getElementById("expand").addEventListener("click", function()
{
if(document.getElementById('unhide').style.display == 'block')
document.getElementById('unhide').style.display = 'none';
else
document.getElementById('unhide').style.display = 'block';
});
you can check the running snippet here
this is pure java script
var button = document.getElementById('button'); // Assumes element with id='button'
button.onclick = function() {
var div = document.getElementById('newpost');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
This worked very well for me, hope it can help someone else. it opens a hidden div in an absolute position and closes it with the same button or the button in the div.
I use it for menu functions.
<div id="myDiv6" style="border:1px solid;background: rgba(255, 255, 255,
0.9);display: none;position: absolute; top: 229px; left: 25%; z-
index:999;height: auto;
width: 500px;">
<h2 >menu item</h2>
what ever you want in the hidden div
<button style="cursor: pointer;border-radius: 12px;background-image: linear-
gradient(to right, red,yellow);font-size:16px;"
onclick="changeStyle6()">Close</button>
</div>
<br/>
<button style="cursor: pointer;border-radius: 12px;background-image: linear-
gradient(to right, red,yellow);font-size:16px;width: 125px;"
onclick="changeStyle6()">button text</button><br/>
<script type="text/javascript">
function changeStyle6(){
var element = document.getElementById("myDiv6");
if(element.style.display == "none") { element.style.display = "block"; }
else { element.style.display = "none"; }
}
</script>

Move one element into another element with remaining elements going to a third location

I am trying to swap elements with the moveButton function. When the user clicks on one of the images is moves the first one to the #good div and then any remaining will go into the #evil div. I have the if/else statement I thought would work.
<div id="character">
<script type="text/javascript">
function moveButton(elem){
if( $(elem).parent().attr("id") == "menu" ){
$(elem).detach().appendTo('#good');
}
else{
$(elem).detach().appendTo('#evil');
}
}
</script>
</div>
<div id="good">
</div>
<div id="evil">
</div>
<div id="menu">
<div class="character" onclick="moveButton(this)" data-name="Chomper">
<p>Chomper</p><p><img width="100" src="http://vignette2.wikia.nocookie.net/plantsvszombies/images/a/a3/Chomper1.png/revision/latest?cb=20090521220057" alt=" + Chomper + "></p><p>Hit Points: 3.55</p>
</div>
<div class="character" onclick="moveButton(this)" data-name="Kernel-pult">
<p>Kernel-pult</p><p><img width="100" src="http://vignette4.wikia.nocookie.net/plantsvszombies/images/c/c4/Kernel-pult1.png/revision/latest?cb=20090521220358" alt=" + Kernel-pult + "></p><p>Hit Points: 1.55</p>
</div>
</div>
Gate your if with a boolean like fiddle
<script type="text/javascript">
var good = false;
function moveButton(elem) {
if ($(elem).parent().attr("id") == "menu" && !good) {
$(elem).detach().appendTo('#good');
} else {
$(elem).detach().appendTo('#evil');
}
good = true;
}
</script>
To send all remaining caracters to evil use $("#menu").find(".character").detach().appendTo('#evil');
like in fiddle 2
<script type="text/javascript">
var good = false;
function moveButton(elem) {
if ($(elem).parent().attr("id") == "menu" && !good) {
$(elem).detach().appendTo('#good');
} else {
$(elem).detach().appendTo('#evil');
}
$("#menu").find(".character").detach().appendTo('#evil');
good = true;
}
</script>
Do not pass THIS to your function, it's already there in the scope. Also using detach() method, you are removing elements from DOM. Try the following...
function moveButton() {
if( $(this).parent().attr("id") == "menu" ) {
$(this).appendTo('#good');
} else {
$(this).appendTo('#evil');
}
}

how do I use the same link to "re-hide" previously hidden text via Javascript?

The below code snippet shows the invite code when I click "Invite Code". But how do I re-hide the invite code if the same link is clicked again? And can it be done where it cycles back and forth with subsequent clicks? I didn't write this code but merely modified it to my use. I am still very new to this type of thing. Thanks!
<style>
div.hide { display:none; }
div.show { text-align:center; }
</style>
<script type='text/javascript'>
function showText(show, hide) {
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
</script>
<br>
<font color="red">-</font>Home<font color="red"> / </font><a onclick="showText('text1')" href="javascript:void(0);">Invite Code</a>-</font>
<div id="text1" class="hide"><font color="red">abc123</font></div>
</center></h3>
Simply use this function:
function showText(id)
{
var elem = document.getElementById(id);
if(elem.style.display == 'none')
{
elem.style.display = 'inline';
}
else
{
elem.style.display = 'none';
}
}
<a onClick="showText('text1');" href="#">Show or Hide</a><br/>
<div style="height: 30px;"><div id="text1" style="display: none;">Text to hide or show... WTF?!</div></div>
<div>This text should not move.</div>
PS: This also works for 2 Elements...
Greetings
I really don't see the use for the show class. You could just toggle the hide class on the elements that you want to toggle.
Assume you dont need the show class, then use the classList.toggle function like this
function toggle(target){
document.getElementById(target).classList.toggle('hide');
}
.hide{ display:none }
<button onclick="toggle('test')">Show / Hide</button>
<div id="test" class="hide">Hello world!</div>
save the state with a boolean
var hided = true;
function showText(show,hide){
if (hided){
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
else{
document.getElementById(show).className = "hide";
document.getElementById(hide).className = "show";
}
hided = !hided;
}
fiddle with this code and some of your html : fiddle,
isn't it the expected behavior ?
<html>
<div ID="content" style="display:block;">This is content.</div>
<script type="text/javascript">
function toggleContent() {
// Get the DOM reference
var contentId = document.getElementById("content");
// Toggle
contentId.style.display == "block" ? contentId.style.display = "none" :
contentId.style.display = "block";
}
</script>
<button onclick="toggleContent()">Toggle</button>
</html>
//Code is pretty self explanatory.

javascript css change overiding css

Sorry for the unclear question title...couldn't think how to put the question in a shirt summary.
I have css to change the background-color of a link when hovered over (with css transistion to fade the color in).
Due the nature of the requirement, I use JS to change the background color of the link which is in use (I have tabs, the selected one's background is selected using JS - getElementById('foo').style.backgroundColor = 'red';).
Even after a tab has been selected, I want the others to change color when hovering.
It works initially but once I have clicked on a tab (JS then changes that tab's color), the hover css style does not work - the other links no longer change color when hovering.
Has anyone else had the same problem?
HTML:
<div class="software_section_selects_wrapper">
<a id="a1" onclick="displayArrow('1')">OVERVIEW</a>
<a id="a2" onclick="displayArrow('2')">SPECS</a>
<a id="a3" onclick="displayArrow('3')">COMMENTS</a>
<div style="clear: both;"></div>
</div>
<div class="section_selects_arrow_wrapper">
<img id="red1"alt="" src="images/red_arrow.png" width="40px" height="20px"/>
<img id="red2"alt="" src="images/red_arrow.png" width="40px" height="20px"/>
<img id="red3"alt="" src="images/red_arrow.png" width="40px" height="20px"/>
</div>
<div id="overview" class="software_overview">
</div>
<div id="specs" class="software_overview">
</div>
<div id="comments" class="software_overview">
</div>
JS:
function displayArrow(arrow) {
var which_arrow = arrow;
if (which_arrow == '1') {
document.getElementById('a1').style.backgroundColor = 'red';
document.getElementById('a2').style.backgroundColor = 'black';
document.getElementById('a3').style.backgroundColor = 'black';
document.getElementById('red1').style.display = 'block';
document.getElementById('red2').style.display = 'none';
document.getElementById('red3').style.display = 'none';
document.getElementById('overview').style.display = 'block';
document.getElementById('specs').style.display = 'none';
document.getElementById('comments').style.display = 'none';
} else if (which_arrow == '2') {
document.getElementById('a2').style.backgroundColor = 'red';
document.getElementById('a1').style.backgroundColor = 'black';
document.getElementById('a3').style.backgroundColor = 'black';
document.getElementById('red2').style.display = 'block';
document.getElementById('red1').style.display = 'none';
document.getElementById('red3').style.display = 'none';
document.getElementById('specs').style.display = 'block';
document.getElementById('overview').style.display = 'none';
document.getElementById('comments').style.display = 'none';
} else {
document.getElementById('a3').style.backgroundColor = 'red';
document.getElementById('a2').style.backgroundColor = 'black';
document.getElementById('a1').style.backgroundColor = 'black';
document.getElementById('red3').style.display = 'block';
document.getElementById('red1').style.display = 'none';
document.getElementById('red2').style.display = 'none';
document.getElementById('comments').style.display = 'block';
document.getElementById('overview').style.display = 'none';
document.getElementById('specs').style.display = 'none';
}
}
This line of code:
document.getElementById('a2').style.backgroundColor = 'black';
adds an inline style which is stronger than :hover styling coming from the stylesheet.
Instead of adding the inline style, reset it to nothing:
document.getElementById('a2').style.backgroundColor = '';
I think his is what you are looking for
<div class="software_section_selects_wrapper">
<a id="a1" onclick="displayArrow('1')" onmouseover="MouseHoverMethod(this)" onmouseout="MouseOutMethod(this)">OVERVIEW</a>
<a id="a2" onclick="displayArrow('2')" onmouseover="MouseHoverMethod(this)" onmouseout="MouseOutMethod(this)">SPECS</a>
<a id="a3" onclick="displayArrow('3')" onmouseover="MouseHoverMethod(this)" onmouseout="MouseOutMethod(this)">COMMENTS</a>
<div style="clear: both;"></div>
</div>
Add following javascript functions and change the color as you need.
function MouseHoverMethod(x) {
x.style.backgroundColor = 'green';
}
function MouseOutMethod(x) {
x.style.backgroundColor = 'black';
}
Your code is far to complicated. You are breaking rule #1 of programming: DRY - Don't repeat yourself.
Also there is no need to set the color with JavaScript, instead set a class to to selected item and use that to style it.
Example: (without the red arrow stuff, because without the style sheet it's difficult to see what you are doing there, and it probably could be replaced with some pure CSS, too):
<div class="software_section_selects_wrapper">
<a onclick="displayTab(this, 'overview')">OVERVIEW</a>
<a onclick="displayTab(this, 'specs')">SPECS</a>
<a onclick="displayTab(this, 'comments')">COMMENTS</a>
<div style="clear: both;"></div>
</div>
<div class="tabs">
<div id="overview" class="software_overview">
</div>
<div id="specs" class="software_overview">
</div>
<div id="comments" class="software_overview">
</div>
</div>
JS:
<script>
function clearClass(elements) {
for (var i = 0; i < elements.length; i++) {
elements[i].className = '';
}
}
function displayTab(link, tabId) {
var links = link.parentNode.getElementsByTagName('a');
clearClass(links);
link.className = 'active';
var tab = document.getElementById(tabId);
var tabs = tab.parentNode.getElementsByTagName('div');
clearClass(tabs);
tab.className = 'active';
}
</script>
CSS:
.tabs > div {
display: none;
}
.tabs > div.active {
display: block;
}
.software_section_selects_wrapper > a {
color: white;
background-color: black;
}
.software_section_selects_wrapper > a.active {
color: white;
background-color: red;
}
Live: http://jsfiddle.net/d9ffnw46/1/
BTW, you should look into using a framework library such as jQuery. As a beginner it makes code such as this much simpler.
EDIT: Here's an example with jQuery: http://jsfiddle.net/d9ffnw46/2/

Categories