How to toggle `<div>` items upon click of another div? - javascript

I have <div> structure like this
<!-- Parent -->
<div id="parentCategory" >
<input type="image" src="a.jpg" onClick="showNextCat('nextCategory1', 'block', 'nextCategory2', 'nextCategory3')" />
<input type="image" src="b.jpg" onClick="showNextCat('nextCategory2', 'block', 'nextCategory1', 'nextCategory3')" />
<input type="image" src="c.jpg" onClick="showNextCat('nextCategory3', 'block', 'nextCategory1', 'nextCategory2')" />
...
</div>
<!-- 1st Child -->
<div id="nextCategory1" style="display: none;">
<input type="image" src="1a.jpg" />
<input type="image" src="1b.jpg" />
</div>
<!-- 2nd Child -->
<div id="nextCategory2" style="display: none;">
<input type="image" src="2a.jpg" />
<input type="image" src="2b.jpg" />
</div>
<!-- 3rd Child -->
<div id="nextCategory3" style="display: none;">
<input type="image" src="3a.jpg" />
<input type="image" src="3b.jpg" />
</div>
My JS
function showNextCat(id, visibility, h1, h2) {
var item = document.getElementById(id);
document.getElementById(h1).style.display = "none";
document.getElementById(h2).style.display = "none";
if (item.style.display !== "none") {
item.style.display = "none";
}
else {
item.style.display = visibility;
}
}
I don't want to hardcode the showNextCat() method to hide non-selected <div>
Please Improvise the JS method.

There are 2 possible option either if you are using jquery
then it will be easier.
Let's see first jQuery's solution
Apply class="category" to all the element which you want to manipulate dynamically.
put value in html want to show like data-show="nextCategory1"
apply css
.category{
display:none;
}
Put this JS function
$('#parentCategory input').on('click',function(e){
$('.category').hide();
$('#'+$(this).data('show')).show();
});
View Fiddle
Now Let's see Javascript solution which is also bit of simillar
function showNextCat(id) {
var item = document.getElementById(id);
var elem = document.querySelectorAll(".category")
var i;
for (i = 0; i < elem.length; i++) {
elem[i].style.display='none';
}
item.style.display='block';
}
View Fiddle2

using jQuery you can make this easy. first thing to do, remove all the onClick events from your buttons. then, you have to define a css class for the selected divs :
.selected {
display : block;
}
then on the buttons, specify the id of the category concerned, for example
<input type="image" src="a.jpg" select-category="nextCategory1" />
all you need to do now, is to define the click event for all the buttons
$("[select-category]").click(function () {
$("#" + $(this).attr("select-category")).toggleClass("selected");
});
Note : this is not the only solutions.

Related

Show images in order of buttons clicked

I'm new to web developing and trying to build a website that shows different flags when clicking buttons.
I encounter some problems when positioning the image... For example, when I click "C -> A -> D -> B ->A", the A flag shows up before other flags and I cannot click again to make it show up twice. Here are my questions.
1) When I click the buttons the images show up in the order of the , not by which button I click first. Is there any way to make the first click one shows up first?
2) What function or code in CSS/javascript/JQuery I can use if I want the image to show up twice or for more times?
Thank you!
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<script>
function showImg( id ) {
for ( i = 1; i < 10; i++) {
}
var obj = document.getElementById( "flag" + id );
if (obj != null)
obj.className = 'show';
}
</script>
<style type="text/css">
.hide{display:none;}
</style>
<input type="button" onclick="showImg(1)" value="A" >
<input type="button" onclick="showImg(2)" value="B">
<input type="button" onclick="showImg(3)" value= "C">
<input type="button" onclick = "showImg(4)" value= "D">
<input type="button" onclick = "showImg(5)" value= "E">
<input type="button" onclick = "showImg(6)" value= "ANS">
<div class="row">
<div class="main">
<div class="screen" position: relative">
<img id="flag1" src="flag1.jpeg" title="1" class="hide" position="static">
</div>
<div position= "relative">
<img id="flag2" src="lag2.jpeg" title="2" class="hide">
<div position= "relative">
<img id="flag3" src="flag3.jpeg" title="3" class="hide">
</div>
<div position= "relative">
<img id="flag4" src="flag4.jpeg" title="4" class="hide">
</div>
<div position= "relative">
<img id="flag5" src="flag5.jpeg" title="5" class="hide">
</div>
<div position= "relative">
<img id="flag6" src="flag6.jpeg" class="hide" position="static">
</div>
</div>
</div>
</div>
</body>
</html>
One approach to the problem is, rather than hiding and showing elements (which relies on those elements being within the DOM already, then showing and hiding them as appropriate which retains their original order), to insert the relevant <img /> elements on clicking the <button> elements.
In the HTML below I've stripped out much of the extraneous HTML in order to simplify the example, and I've converted your <input type="button" /> elements into <button> elements, which allows those elements to contain HTML and allows us to use generated content in the pseudo-elements, ::before and ::after:
// here we select all <button> elements that have a "data-src"
// attribute:
const buttons = document.querySelectorAll('button[data-src]'),
// creating a named function to handle inserting the
// elements:
insertImage = function() {
// the 'this' is passed automatically from the later
// use of EventTarget.addEventListener() method, here
// we cache that within a variable:
let clicked = this,
// we retrieve the element, via its id, into which
// we wish to append the elements:
output = document.getElementById('gallery'),
// we create an <img> element:
image = document.createElement('img');
// we use a template literal to set the 'src'
// property-value to the 'https' protocol
// coupled with the data-src attribute-value
// retrieved via the Element.dataset API:
image.src = `https://${clicked.dataset.src}`;
// and append the <img> to the desired element:
output.append(image);
};
// here we iterate over the NodeList of <button> elements
// retrieved earlier, using NodeList.prototype.forEach():
buttons.forEach(
// along with an Arrow function to the attach the
// insertImage function (note the deliberate lack of
// parentheses) via the EventTarget.addEventListener()
// method:
(btn) => btn.addEventListener('click', insertImage)
);
/*
using the ::before pseudo-element, with generated
content, to add text to the button elements that
have a data-src attribute:
*/
button[data-src]::before {
content: 'Show image ' attr(value);
}
#gallery {
display: grid;
grid-template-columns: repeat(auto-fill, 180px);
grid-gap: 1em;
align-content: center;
justify-content: center;
}
<!--
here we have three <button> elements, each with a data-src
custom attribute that contains the src of the relevant image:
-->
<button type="button" value="A" data-src="i.stack.imgur.com/4CAZu.jpg"></button>
<button type="button" value="B" data-src="i.stack.imgur.com/SqYhm.gif"></button>
<button type="button" value="C" data-src="i.stack.imgur.com/a9xXV.png"></button>
<div id="gallery"></div>

html checkbox list that shows and hides links when filtered

I have written code that creates a checkbox list where when i click the checkbox below my list of options i would like a link to show underneath that the user can click (show/hide) I cannot figure out why my code will not work. If the user unchecked the box the link disappears but nothing happens when i click my check boxes. I would like to do this fix in JQuery
<!DOCTYPE html>
<html>
<div class ="container">
<head></head>
<body>
<input id="grp1" type="checkbox" value="group_1" onClick="http://google.com" />
<label for="grp1"> group 1 </label>
<div>
<input id="grp2" type="checkbox" value="group_2" onClick="http://google.com" >
group_2</label>
</div>
</body>
</html>
You'll have to use javascript to hide/show the wanted elements in html. There are many approaches to this. The most basic one would be something like
<!DOCTYPE html>
<html>
<body>
<div id="container">
<input id="grp1" type="checkbox" value="group_1"/>
<label for="grp1"> group 1 </label>
<br>
<input id="grp2" type="checkbox" value="group_2"/>
<label for="grp2"> group_2</label>
<!--hidden elements using css-->
Link for group_1
<br>
Link for group_2
</div>
<script>
//listen to the click event on the whole container
document.getElementById("container").onclick = function (e) {
//check every box if it's checked
if (document.getElementById('grp1').checked) {
document.getElementById('url1').style.display = 'block';
} else {
document.getElementById('url1').style.display = 'none';
}
if (document.getElementById('grp2').checked) {
document.getElementById('url2').style.display = 'block';
} else {
document.getElementById('url2').style.display = 'none';
}
}
</script>
</body>
</html>
Of course you can use different approaches like creating the element in javascript then adding it to the html if you don't like the idea if existing hidden elements. You might also use loops to loop through checkbox element and simply show/hide the url accordingly. And more to make the code flexible on any number of boxes. Something like this
<!DOCTYPE html>
<html>
<body>
<div id="container">
<div id="checkBoxContainer">
<input id="grp1" type="checkbox" value="group_1"/>
<label for="grp1"> group 1 </label>
<br>
<input id="grp2" type="checkbox" value="group_2"/>
<label for="grp2"> group_2</label>
</div>
<!--hidden elements using css-->
Link for group_1
<br>
Link for group_2
</div>
<script>
//listen to the click event on the whole container
document.getElementById("checkBoxContainer").onclick = function (e) {
var linkNumber = 1; //This is number of the first url element with ud url1
var containerChildren = document.getElementById("checkBoxContainer").children;
//loop through the children elements
for (var i = 0; i < containerChildren.length; i++) {
var oneChild = containerChildren[i]; //catch only one child in a variable
//simply filter the input elements which are of type checkbox
if(oneChild.tagName === "INPUT" && oneChild.type === "checkbox"){
//Show or hide the url accordingly.
if (oneChild.checked) {
document.getElementById('url' + linkNumber++).style.display = 'block';
} else {
document.getElementById('url' + linkNumber++).style.display = 'none';
}
}
}
}
</script>
</body>
</html>
The onclick HTML attribute doesn't work that way. The attribute value is executed as javascript. You can make a js function to show/hide the link.
Hi you want to try this:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.group-link{
display: block;
}
.hidden{
display: none;
}
</style>
</head>
<body>
<div class="jsParent">
<label for="grp1">
<input id="grp1" type="checkbox" value="group_1" onchange="showLink(this)"/> group 1
</label>
<a class="group-link hidden jsLink" href="https://www.animalplanet.com/tv-shows/dogs-101/videos/the-doberman">Group 1 Link</a>
</div>
<div class="jsParent">
<label for="grp2">
<input id="grp2" type="checkbox" value="group_2" onchange="showLink(this)"/> group_2
</label>
<a class="group-link hidden jsLink" href="https://www.animalplanet.com/tv-shows/cats-101/videos/ragdoll">Group 2Link </a>
</div>
<script type="text/javascript">
function showLink(el){
var parent = el.parentElement.parentElement;
var linkEl = getAnchorEl(parent);
if(linkEl){
if(el.checked){
linkEl.classList = linkEl.classList.value.replace('hidden', '');
}else{
linkEl.classList = linkEl.classList.value + ' hidden';
}
}
}
function getAnchorEl(parent){
var childrens = parent.children;
var linkEl = null;
for (var i = 0; i < childrens.length; i++) {
var childEl = childrens[i];
if(childEl.classList.value.indexOf('jsLink') > -1){
linkEl = childEl;
break;
}
}
return linkEl;
}
</script>
</body>
</html>
Your question is undoubtedly a duplicate but I am answering because I would like to help you identify issues with the code you posted.
I notice you have a <div>tag between your tag and tag. Why? This is a bit of an over simplification but as a general rule never put anything between your <html> and <head> tag and only place <div> tags inside your <body> tag. Also be mindful of how you nest your elements. That tag starts after and before .
Even if that were correct placement you close the before you close your div arbitrarily in the middle of your body tag. you should never have
<div>
<p>
</div>
</p>
Instead it should look like this
<div>
<p>
</p>
</div>
In your onClick attribute you have a random URL. That will not open a new window. You new too put some javascript in there.
<input onClick="window.open('http://google.com')">
Also your second label tag does not have an opening, just a </label> close tag
To answer your question - I suggest you look at the jQuery toggle function.
<input type="checkbox" id="displayLink" />
Google
<script type="text/javascript">
$("#displayLink").click(function(){
$("#googleLink").toggle();
});
</script>
As a general rule you should favor event handlers (such as the $("").click() posted above) to handle events (like clicking) as opposed to html attributes such as onClick.

Saving checkbox values causes issues with showing/hiding linked image

I have written a code to show or hide a picture based on the value of corresponding checkboxes. I was able to have the picture shown or hidden on reload if 'checked="checked"' is written into the checkbox.
I was able to write a code to save the value of the checkbox but then the picture is no longer tethered to the checked/unchecked value and changes with reload.
My end goal is to have the a checked checkbox to show the picture and unchecked checkbox to hide the picture and I need the value saved to allow the correct value to work on reload after a change has been made.
This is just a small snip of the overall code. The whole thing is a series of 64 checkboxes linked to 64 different pictures, which overlay a mapped background image.
I should also mention that this will ultimately be used for a SharePoint site, if that makes a difference.
Thanks in advance for any help!!
(There is a link to jsfiddle demo at the bottom)
HTML:
<a href="home.aspx">
<p id="A1R1" style="left:146px;top:256px;position:absolute;z-index:inherit;" class="hidden">
<img id="A1R1" alt="A1R1" src="red.jpg" width="108" height="60" />
</p>
</a>
<a href="home2.aspx">
<p id="A2R2" style="left:273px;top:256px;position:absolute;z-index:inherit;" class="hidden">
<img id="A2R2" alt="A2R2" src="green.html" width="108" height="60" />
</p>
</a>
<fieldset class="fieldset-auto-width" style="width:165px">
<center>
<p style="font-size:25px">Show/Hide</p>
</center>
<fieldset class="fieldset-auto-width" style="width:150px">
<center>A1 Green/Red
<p>
</center>
<center>
<input type="checkbox" id="A1G" checked="checked" /> </center>
</fieldset>
<fieldset class="fieldset-auto-width" style="width:150px">
<center>A2 Green/Red
<p>
</center>
<center>
<input type="checkbox" id="A2G" checked="checked" /> </center>
</fieldset>
</fieldset>
<center>
<input type="button" id="ReserveerButton1" value="save" onclick="save()" />
<input type="button" id="Wisbutton1" value="delete" onclick="wis()" />
</center>
JQUERY:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
(function(i, $) {
var $A_1_G = $('#A1G'),
$A_1_R_1 = $('#A1R1');
var toggleMain = function() {
$A_1_R_1.slideToggle();
};
if ($A_1_G.is(':checked')) {
toggleMain();
}
$A_1_G.on('click', toggleMain);
})(document, jQuery);
(function(i, $) {
var $A_2_G = $('#A2G'),
$A_2_R_2 = $('#A2R2');
var toggleMain = function() {
$A_2_R_2.slideToggle();
};
if ($A_2_G.is(':checked')) {
toggleMain();
}
$A_2_G.on('click', toggleMain);
})(document, jQuery);
</script>
Javascript:
function save() {
var checkbox = document.getElementById('A1G');
localStorage.setItem('A1G', checkbox.checked);
var checkbox = document.getElementById('A2G');
localStorage.setItem('A2G', checkbox.checked);
}
function load() {
var checked = JSON.parse(localStorage.getItem('A1G'));
document.getElementById("A1G").checked = checked;
var checked = JSON.parse(localStorage.getItem('A2G'));
document.getElementById("A2G").checked = checked;
}
function wis() {
location.reload();
localStorage.clear()
}
load();
Link to fiddle code
This seems to take care of it: http://jsfiddle.net/w0yL5njs/
Move your 'toggleMain w/ jQuery' code block to after your 'save/load' code block, so that the checkboxes will be pre-checked before the images' initial visibility are set.
So the order of your <script> tags will be
a) <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
b) The script that uses jQuery.
c) your save/load script that doesn't use jQuery.
Actually, (b) and (c) can be in the same <script> but (a) must be separate.
Add display:none to the <p> containing the images.
Is that what class="hidden" was intended to do? You could add .hidden { display: none; } to your CSS...
// Remove
if ($A_1_G.is(':checked')) {
toggleMain();
}
// ADD
if ($A_1_G.is(':checked')) {
$A_1_R_1.show();
}else{
$A_1_R_1.hide();
}
//remove
if ($A_2_G.is(':checked')) {
toggleMain();
}
if ($A_2_G.is(':checked')) {
$A_2_G.show();
}else{
$A_2_G.hide();
}

How to Direct url When All ID on DIV click

I want make mini game but stuck with logic code.
Try see my code below,,,
I want to direct after click all div ID wrong1, wrong2, wrong3, then wrong4 (the last) its value for direct. Something add class maybe.
I want before the last click ID wrong4, The ID wrong4 its addclass rightAnswers. Because class rightAnswers have attribute html5 data-current-game="5" data-next-game="finish" for next result page.
I have try make it and helping by https://stackoverflow.com/users/2025923/tushar
Helping by Tushar, How to show last ID when All ID on DIV click,
But now i want different logic.
Thank you
Note :
I have try edit like this,
But the class rightAnswers not function ...
divs.splice(divs.indexOf($(this).prop("id")), 1)
if (divs.length == 0) {
$('#wrong1, #wrong2, #wrong3, #wrong4').addClass('rightAnswers');
}
And add script url direction like this :
But the class rightAnswers still not function
$(".rightAnswers").click(function() {
window.location = "/game/result";
});
Code From How to show last ID when All ID on DIV click
$(function () {
var divs = ["wrong1", "wrong2", "wrong3", "wrong4"];
$('#wrong1, #wrong2, #wrong3, #wrong4').click(function () {
$(this).animate({
opacity: 0,
top: 100,
}, 500);
divs.splice(divs.indexOf($(this).prop("id")),1)
if(divs.length == 0){
$('#wrong-gameOne').eq(0).hide();
$('#correct-gameOne').eq(0).show();
}
});
});
<img id="correct-gameOne" class="rightAnswer" src="http://authentic-scandinavia.com/system/images/tours/photos/10/thumbnail.jpg" data-current-game="1" data-next-game="2" style="display:none;" />
<img id="wrong-gameOne" class="wrongAnswer" src="http://authentic-scandinavia.com/system/images/tours/photos/125/thumbnail.jpg" data-current-game="1" data-next-game="2" />
<div id="wrong1" class="no-bottom">
<label>TEXT 1</label>
</div>
<div id="wrong2" class="no-bottom">
<label>TEXT 2</label>
</div>
<div id="wrong3" class="no-bottom">
<label>TEXT 3</label>
</div>
<div id="wrong4" class="no-bottom">
<label>TEXT 4</label>
</div>

is it possible to hide div when another button is click?

I am trying to hide the div's when different buttons are clicked but I don't know how to. (So when 'Test 1' is clicked it should hide 'Test 2' Div and vice versa) I checked here and on Google but couldn't find an answer for it.
Javascript :
function showHide(divId) {
var theDiv = document.getElementById(divId);
if (theDiv.style.display == "none") {
theDiv.style.display = "";
} else {
theDiv.style.display = "none";
}
}
HTML :
<input type="button" onclick="showHide('hidethis')" value="Test It">
<div id="hidethis" style="display:none">
<h1>TEST ME!</h1>>
</div>
<input type="button" onclick="showHide('hidethis2')" value="Test It 2">
<div id="hidethis2" style="display:none">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
JSFIDDLE: is not doing it here but works locallyhttp://jsfiddle.net/S5JzK/
<input type="button" onclick="showHide('hidethis')" value="Test It" />
<div id="hidethis" style="display:none">
<h1>TEST ME!</h1>
</div>
<input type="button" onclick="showHide('hidethis2')" value="Test It 2">
<div id="hidethis2" style="display:none">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
function showHide(divId) {
$("#"+divId).toggle();
}
Check the Fiddle http://jsfiddle.net/S5JzK/7/
Please try this, it works well and so simple,
<html>
<head>
<style>
.manageDiv{
display:none;
}
</style>
</head>
<body>
<input type="button" class="testButton" value="Test It" />
<input type="button" class="testButton" value="Test It 2" />
<div id="hidethis2" class="manageDiv">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
</body>
</html>
$(function(){
$(".testButton").on("click", function(){
$("#hidethis2").toggleClass("manageDiv");
});
});
To it work in fiddle, in your example, you need to select (No wrap - in head) on the left.
Look the example below, using pure javascript:
HTML
<input type="button" onclick="showHide('hidethis')" value="Test It">
<div id="hidethis" style="display:none">
<h1>TEST ME!</h1>
</div>
<input type="button" onclick="showHide('hidethis2')" value="Test It 2">
<div id="hidethis2" style="display:none">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
JAVASCRIPT
function showHide(divId) {
/* Hide all divs */
var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = "none";
}
/* Set display */
var theDiv = document.getElementById(divId);
theDiv.style.display = "";
}
http://jsfiddle.net/S5JzK/9/
ANOTHER JAVASCRIPT EXAMPLE
function showHide(divId) {
/* Hide the divs that you want */
var div1 = document.getElementById('#hidethis');
var div2 = document.getElementById('#hidethis2');
div1.style.display = "none";
div2.style.display = "none";
/* Set display */
var theDiv = document.getElementById(divId);
theDiv.style.display = "";
}
Using JQuery:
function showHideDiv(divId, bShow) {
if (bShow) {
$("#" + divId).show();
} else {
$("#" + divId).hide();
}
}
your code seems fine. are you sure you enter the function upon click? try adding a breakpoint using developer tools or an alert.
Anyways, I see you tagged this post with jquery. you can you it to do the task more elegantly.
$("#" + theDiv).hide();
or for showing it:
$("#" + theDiv).show();
"JSFIDDLE: is not doing it here but works locally"
Yes, because by default jsfiddle wraps your JS in an onload handler, which means the function declaration is local to that handler. Inline html attribute event handlers like your onclick="showHide('hidethis')" can only call global functions.
Under jsfiddle's Frameworks & Extensions heading there's a drop-down where you can change the default "onload" to "No wrap - in head" (or "No wrap - in body"). That'll make your function declaration global as in your local implementation.
Demo: http://jsfiddle.net/S5JzK/8/

Categories

Resources