Div Hide And Show - javascript

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>

Related

Change elements display order after click event - javascript

After i click on Calculate button "Reset" button appears below it, but i want to change the display styles how they both appear after the click event. I want them side by side and not on top of each other (picture in link represents the idea) I tried doing it by toggling a class after click, but in that way i could change only one element appearance. What would be the best way to do it?
Button order example
HTML code
<div class="container">
<header>
<div class="h1-background">
<h1 class="h1">Tip calculator</h1>
</div>
</header>
<div class="text">
<p>How much was your bill?</p>
<form name="theForm3">
<input class="input-bill" placeholder="Bill Amount $">
<p>How big tip will you give?</p>
<!-- DROP DOWN-->
<div class="select">
<select class="percents">
<option value="1">Nothing</option>
<option value="0.5">5%</option>
<option value="0.10">10%</option>
<option value="0.15">15%</option>
<option value="0.20">20%</option>
<option value="0.30">30%</option>
</select>
</div>
</form>
<!-- AFTER DROP DOWN-->
<p>How many people are sharing the bill?</p>
<input class="input-people" placeholder="Number of people">
<button onclick="calculateTip(), changeStyle()" class=" button center button-calc"
type="button">Calculate
</button>
<button onclick="" class=" button center reset-button" type="button">Reset
</button>
JS CODE
"use strict";
const buttonCalc = document.querySelector(".button-calc");
function calculateTip() {
//Selectors
const inputBill = document.querySelector(".input-bill").value;
let inputPeople = document.querySelector(".input-people").value;
const percents = document.querySelector(".percents").value;
//Event listeners
//validate input
if (inputBill === "" || percents == 0) {
alert("Please enter values");
return;
}
//Check to see if this input is empty or less than or equal to 1
if (inputPeople === "" || inputPeople <= 1) {
inputPeople = 1;
document.querySelector(".each").style.display = "none";
} else {
document.querySelector(".each").style.display = "block";
}
//Functions
let total = (inputBill * percents) / inputPeople;
console.log(total);
//round to two decimal places
total = Math.round(total * 100) / 100;
//next line allows us to always have two digits after decimal point
total = total.toFixed(2);
//Display the tip
// Display alert i there is no TIP
if (percents == 1) {
alert(`There is no tip, you must pay only the bill $${total}`)
return;
}
document.querySelector(".reset-button").style.display = "block";
document.querySelector(".totalTip").style.display = "block";
document.querySelector(".tip").innerHTML = total;
}
function changeStyle() {
let container = document.querySelector(".container");
container.style.height = "400px";
event.preventDefault();
}
//Hide the tip amount on load
document.querySelector(".reset-button").style.display = "none";
document.querySelector(".totalTip").style.display = "none";
document.querySelector(".each").style.display = "none";
If I understand your question, create another div for those buttons, then try to put display flex.
Put you buttons in a container like this and then toggle the class between "action-row" and "actions-column" to get the desired result,
<div id="actions" class="actions-row">
<button onclick="calculateTip(), changeStyle()" class=" button center button-calc"
type="button">Calculate
</button>
<button onclick="" class=" button center reset-button" type="button">Reset
</button>
</div>
then in your calculateTip function add this line to toggle between the classes:
document.getElementById("actions").className = "actions-row";
and then in the hide the tip amount on load add:
document.getElementById("actions").className = "actions-column";
Then in your css create the following:
.actions-row{
display: flex;
flex-direction: row;
flex-wrap: nowrap;
}
.actions-column{
display: flex;
flex-direction: column;
flex-wrap: nowrap;
}

How to hide all divs of same class using onclick? [duplicate]

This question already has answers here:
Equivalent of getElementById for Classes in Javascript
(6 answers)
Closed 2 years ago.
As you can see by running the snippet 1 div isn't hiding , I'm a newbie so I don't know what to do? Can someone explain what's wrong? I can't figure it out.
var x = document.getElementById("jobs");
function openandcloseavjobs() {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
#jobs{
height: 100px;
width:100px;
background-color:orange;
margin: 20px;
}
<button onclick="openandcloseavjobs()">Average Pay</button>
<div id="jobs">
<h3>job 1</h3>
</div>
<div id="jobs">
<h3>job 2</h3>
</div>
You need to use a class and use querySelectorAll method to get all element with same class name .jobs using forEach function to loop through all the elements and then use display none or block on all found element with that class name.
Also, where possible do not use inline events like onClick etc use addEventListener with a click instead.
Live Demo:
var getEl = document.querySelectorAll(".jobs"); //get all element .jobs
var btn = document.querySelector("#getAvg"); //get the btn
//Button click function
btn.addEventListener('click', function() {
getEl.forEach(function(item) { //forEach elements
if (item.style.display === "none") {
item.style.display = "block";
} else {
item.style.display = "none";
}
})
}, false);
.jobs {
height: 100px;
width: 100px;
background-color: orange;
margin: 20px;
}
<button id="getAvg">Average Pay</button>
<div class="jobs">
<h3>job 1</h3>
</div>
<div class="jobs">
<h3>job 2</h3>
</div>
The problem is that the function getElementById only finds 1 element as the name suggests.
You should try with class names so change the to and use the function getElementsByClassName("example").
You are using id (identifier, which, by definition should be unique) to select multiple elements. To achieve what you want, use a class
var X = document.getElementsByClassName("jobs");
function openandcloseavjobs() {
for (let x of X) {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
}
.jobs{
height: 100px;
width:100px;
background-color:orange;
margin: 20px;
}
<button onclick="openandcloseavjobs()">Average Pay</button>
<div class="jobs">
<h3>job 1</h3>
</div>
<div class="jobs">
<h3>job 2</h3>
</div>

How to make a JavaScript function control two HTML IDs?

I have this button tag element
<button class="btn btn-link" type="button" onclick="contentDownloads()">
<img src="./downloads/content-textures.svg" width="120px" />
</button>
And has a javascript function
function contentDownloads() {
var x = document.getElementById("vipDownloads");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
But, in the future I will include more buttons and would lead to the same function.
This is the part that contains the IDs:
<div id="vipDownloads" class="collapse show" style="display: none;">
<div class="card-body">
<h5 class="card-title">Map Pack v 1.8 <span class="caption-entry">by cWaLker</span> </h5>
<p class="card-text">
Aight Fellas,
Map Pack v 1.8 introduces some revived classics and under the radar stunners. <br>
<br> 1.7 went on a diet and dropped some restraining pounds.
For this nugget to work stable, you'd need to remove your own user folder first and then drop the User folder from the 1.8 bulk package.. it will serve you everything you need anyways ;-)<br>
<br> Have Fun Guys lets kick some flips!
</p>
<button type="button" class="btn btn-outline-success">Download</button><br>
</div>
</div>
You can see here how I designed the buttons and content http://thpsblog.000webhostapp.com/downloads.html (the css on my host takes a while to actually update, might include some white on white colors)
The function hides and unhides content.
I have found some solutions but they were all typed in jQuery, and unfortunately I do not know jQuery.
How could I make this function take two unique ids?
Make the ID of the element to toggle a parameter of the function, and pass it when you call the function.
function contentDownloads(id) {
var x = document.getElementById(id);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button class="btn btn-link" type="button" onclick="contentDownloads('vipDownloads')">
<img src="./downloads/content-textures.svg" width="120px" />
</button>
If you don't want to add an onclick event to your html, you can create a vars array and use a forEach loop. Else, you can use #Barmar's answer.
function contentDownloads() {
var x = document.getElementById("vipDownloads");
var y = document.getElementById("y");
var z = document.getElementById("z");
vars = [x,y,z]; // update this array when selected a new element
vars.forEach(function(p){
if (p.style.display === "none") {
p.style.display = "block";
} else {
p.style.display = "none";
}
})
}
Make id param as others suggested or use data attributes:
<button class="btn btn-link" type="button" onclick="contentDownloads(this)" data-downloadsid="vipDownloads">
<img src="./downloads/content-textures.svg" width="120px" />
</button>
function contentDownloads(element) {
var x = document.getElementById(element.dataset.downloadsid);
if(x == null) return;
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
You can query the elements with a class and iterate each
<div class="download-element">Element 1</div>
<div class="download-element">Element 2</div>
<div class="download-element">Element 3</div>
<button class="btn btn-link" type="button" onclick="contentDownloads()">
<img src="./downloads/content-textures.svg" width="120px" />
</button>
function contentDownloads() {
document.querySelectorAll('.download-element')
.forEach(element => {
if(element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
})
}

How to toggle close all divs when another div is opened

I have a long streak of divs with the following structure:
<div id="income">
<h5 onclick="toggle_visibility('incometoggle');">INCOME</h5>
<div id="incometoggle">
<h6>Income Total</h6>
</div>
</div>
<div id="income2">
<h5 onclick="toggle_visibility('incometoggle2');">INCOME2</h5>
<div id="incometoggle2" style="display:none;">
<h6>Income Total2</h6>
</div>
</div>
<div id="income3">
<h5 onclick="toggle_visibility('incometoggle3');">INCOME3</h5>
<div id="incometoggle3" style="display:none;">
<h6>Income Total3</h6>
</div>
</div>
I have this code to make them open and close:
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'none') e.style.display = 'block';
else e.style.display = 'none';
}
At site load, the first div is opened, the rest is closed.
http://jsfiddle.net/txa2x9qq/3/
How can I make the first div close when the second one is opened, and so on - to have only one opened at a time?
Thank you
This way you just open the next on the close of the previus
function toggle_visibility(id,next) {
var e = document.getElementById(id);
if (e.style.display == 'none') e.style.display = 'block';
else e.style.display = 'none';
if (next != undefined)
{
toggle_visibility(next);
}
}
call it like:
<h5 onclick="toggle_visibility('incometoggle','incometoggle2');">INCOME</h5>
http://jsfiddle.net/txa2x9qq/3/
You can use jQuery Start with Selector to hide all div starting with incometoggle and use not() to exclude the current div
See below function
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'none') e.style.display = 'block';
else e.style.display = 'none';
// hide all div except current
$('div[id^=incometoggle]').not('#'+id).hide();
}
DEMO
EDIT - you can write whole logic in jQuery only, just bind click event to h5 elements and show / hide div next to it using toggle. And hide all div except current using jQuery Start with Selector
$(function() {
$('h5').click(function(){
var incomeDiv = $(this).next('div');
$(incomeDiv).toggle();
$('div[id^=incometoggle]').not(incomeDiv).hide();
});
});
DEMO Using JQuery
You can use jQuery more easily:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
function toggle_visibility(id) {
$("div[id^='incometoggle']").hide();
$('#'+id).show();
}
</script>
I would approach it slightly differently and use a class along with a jquery selector -
<div id="income">
<h5 onclick="toggle_visibility('incometoggle');">INCOME</h5>
<div id="incometoggle" class="income-total">
<h6>Income Total</h6>
</div>
</div>
...
function toggle_visibility(id) {
// hide all divs with class income-total
$('.income-total').hide();
// show the desired div
$('#' + id).show();
}
Using just Vanilla Javascript, like you're actually doing at the moment:
function toggle_visibility(id) {
// Your clicked element
var e = document.getElementById(id);
// List containing all the divs which id starts with incometoggle.
var allDivs = document.querySelectorAll('div[id^=incometoggle]');
// Loop through the list and hide the divs, except the clicked one.
[].forEach.call(allDivs, function(div) {
if (div != e) {
div.style.display = 'none';
}
else {
e.style.display = e.style.display == 'none' ? 'block' : 'none';
}
});
}
Demo
If you want to do in pure java script then this solution will work for you.
<div id="income">
<h5 onclick="toggle_visibility('incometoggle');">INCOME</h5>
<div id="incometoggle" class="income">
<h6>Income Total</h6>
</div>
</div>
<div id="income2">
<h5 onclick="toggle_visibility('incometoggle2');">INCOME2</h5>
<div id="incometoggle2" style="display:none;" class="income">
<h6>Income Total2</h6>
</div>
</div>
<div id="income3">
<h5 onclick="toggle_visibility('incometoggle3');">INCOME3</h5>
<div id="incometoggle3" style="display:none;" class="income">
<h6>Income Total3</h6>
</div>
</div>
function toggle_visibility(id) {
var e = document.getElementById(id);
var myClasses = document.querySelectorAll('.income'),
i = 0,
l = myClasses.length;
for (i; i < l; i++) {
myClasses[i].style.display = 'none';
}
if (e.style.display == 'none') e.style.display = 'block';
}
DEMO

Javascript if and else runs simultaneously

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

Categories