So, I'm doing my designer-portfolio in html and I wanted to have a menu that only shows when this character is pressed...
But I'm new on programming and my codes are very simple, so I'm using this:
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.visibility == 'hidden')
e.style.visibility = 'visible';
else
e.style.visibility = 'hidden';
}
function untoggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.visibility == 'visible')
e.style.visibility = 'hidden';
else
e.style.visibility = 'visible';
}
<div id="openmenu" style="visibility: visible;" onclick="toggle_visibility('menu'); onclick=toggle_visibility('closemenu');">openmenu</div>
<div id="closemenu" style="visibility: hidden;" onclick="untoggle_visibility('menu'); onclick=untoggle_visibility('closemenu');">closemenu</div>
<div id="menu" style="visibility: hidden;">...</div>
The problem is it only works once...
When I click on #openmenu it shows the #menu and the #closemenu, and when I click on #closemenu it hiddes the #menu and the #closemenu.
BUT it only works once, so if I press #openmenu after #closemenu, it won't work...
Your code is wrong.
onclick="toggle_visibility('menu'); onclick=toggle_visibility('closemenu');"
So what happens with the above code is it runs once. And when it runs it reassigns onclick because you have onclick=functionCall
So after it runs you basically have <div onclick=undefined> because the function did not run.
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.visibility == 'hidden')
e.style.visibility = 'visible';
else
e.style.visibility = 'hidden';
}
function untoggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.visibility == 'visible')
e.style.visibility = 'hidden';
else
e.style.visibility = 'visible';
}
<div id="openmenu" style="visibility: visible;" onclick="toggle_visibility('menu');toggle_visibility('closemenu');">openmenu</div>
<div id="closemenu" style="visibility: hidden;" onclick="untoggle_visibility('menu');untoggle_visibility('closemenu');">closemenu</div>
<div id="menu" style="visibility: hidden;">...</div>
How would most people code it? By toggling a class.
function toggle_visibility(ids) {
ids.forEach( function (id) {
var elem = document.getElementById(id);
elem.classList.toggle('visibilityHidden')
})
}
.visibilityHidden {
visibility: hidden;
}
/* use hidden if you do not want it to take up space */
.hidden {
display: none;
}
<div id="openmenu" onclick="toggle_visibility(['menu','openmenu','closemenu']);">openmenu</div>
<div id="closemenu" class="visibilityHidden" onclick="toggle_visibility(['menu','openmenu','closemenu']);">closemenu</div>
<div id="menu" class="visibilityHidden">...</div>
Most developers would not use inline event handlers either, but that is a different question.
Related
Here is my code:
<form>
White
<input id="white" type="checkbox" onclick="checkMe()"/>
<img id="www" style="display: none;" src="assets/2.jfif" alt="shirt">
</form>
<script>
function checkMe(){
var cb = document.getElementById("white");
var img = document.getElementById("www");
if(cb.checked==true){
text.style.display="block";
} else {
text.style.display="none";
}
}
</script>
The checkbox is indicating that it is being checked but the image is not displaying. Ive tried possible solutions but none have helped. Any insights will be appreciated.
Found the solution.
text.style.display="block";
text.style.display="none";
Replace text with img
var cb = document.getElementById("white");
var img = document.getElementById("www");
function checkMe() {
if (cb.checked == true) {
img.style.display = "block";
} else {
img.style.display = "none";
}
}
<input id="white" type="checkbox" onclick="checkMe()" />
<img id="www" style="display: none;" src="https://sample-videos.com/img/Sample-png-image-100kb.png" alt="shirt">
Simple Method - without Js
img {
display: none
}
input {
height: 30px;
width: 30px;
}
input:checked +img {
display: block
}
<input type="checkbox" />
<img src="https://sample-videos.com/img/Sample-png-image-100kb.png" >
You Just need to Replace the wrong selector with your image selector variable into the JavaScript function.
Below Is the function I'm sharing with you. You should replace this function with the old one.
function checkMe() {
var cb = document.getElementById("white");
var img = document.getElementById("www");
if (cb.checked == true) {
img.style.display = "block";
} else {
img.style.display = "none";
}
}
I'm very new to using Javascript and i'm struggling how I can achieve what I am after. I've created 4 buttons using;
<input type="button" name="answer" value="Brave" onclick="showDiv()">
My goal is that if you click on the button, it changes state and the div appears (got that far). If I click another button, i'd like the content to hide the previous div selected and show the one they had just clicked.
Any help/guidance would really be appreciated.
function showDiv() {
document.getElementById('BraveDiv').style.display = "block";
}
function showDiv1() {
document.getElementById('DeterminedDiv').style.display = "block";
}
function showDiv2() {
document.getElementById('CompassionateDiv').style.display = "block";
}
function showDiv3() {
document.getElementById('ConsiderateDiv').style.display = "block";
}
My aim is that if you was to click
function showDiv()
{
document.getElementById('new1').style.display = "block";
document.getElementById('Div1').style.display = "none";
document.getElementById('Div2').style.display = "none";
}
function showDiv1()
{
document.getElementById('Div1').style.display = "block";
document.getElementById('new1').style.display = "none";
document.getElementById('Div2').style.display = "none";
}
function showDiv2()
{
document.getElementById('Div2').style.display = "block";
document.getElementById('new1').style.display = "none";
document.getElementById('Div1').style.display = "none";
}
Your code attached won't achieve any of the results you're looking for, however, it's obvious what you're looking for.
You buttons should look like the following :
<button role="button" onclick="showDiv('BraveDiv')">Brave</button>
Here, the role prevents the default behaviour of submit. The onclick tells the button what to do when you click it, and the "BraveDiv" is the parameter we will pass to the function, telling it which div to display.
The DIV associated with the above button, should look as follows :
<div id="BraveDiv" style="display: none;"> SOME CONTENT HERE </div>
Here you'll notice the ID is equal to the parameter we mentioned above.
And your JavaScript should work as follows :
<script>
function showDiv(elem){
document.getElementById(elem).style.display = "block";
}
</script>
I've attached a working snipped example as below, just click "Run code snippet" to view the snippet and test the code.
function showDiv(elem) {
document.getElementById(elem).style.display = "block";
}
<button role="button" onclick="showDiv('BraveDiv')">Brave</button>
<button role="button" onclick="showDiv('CompassionateDiv')">Compassionate</button>
<div id="BraveDiv" style="display: none;"> SOME BRAVE CONTENT HERE </div>
<div id="CompassionateDiv" style="display: none;"> SOME COMPASSIONATE CONTENT HERE </div>
The above, however, will only SHOW YOUR DIVS.
The full jQuery solution to this (hide/show as per the tag) would be :
<script>
function showDiv(elem) { // When the button is pressed
$("div").each(function() { // For each Div
if ($(this).attr('id') != elem) { // If the Div's id is not equal to the parameter
$(this).css("display", "none");
} // HIDE IT
else {
$(this).css("display", "block"); // SHow It
});
</script>
If you are unfamiliar with jQuery and would prefer a JavaScript only solution, then :
<script>
function showDiv(elem){
var divsToCheck = ["BraveDiv", "CompassionateDiv"]; // Add to here to check more divs
for(let i = 0; i < divsToCheck.length; i++){
if(divsToCheck[i] == elem){
document.getElementById(divsToCheck[i]).style.display = "block";
}
else{
document.getElementById(divsToCheck[i]).style.display = "none";
}
}
</script>
Again I've attached a snippet below.
function showDiv(elem) {
var divsToCheck = ["BraveDiv", "CompassionateDiv"]; // Add to here to check more divs
for (var i = 0; i < divsToCheck.length; i++) {
if (divsToCheck[i] == elem) {
document.getElementById(divsToCheck[i]).style.display = "block";
} else {
document.getElementById(divsToCheck[i]).style.display = "none";
}
}
}
<button role="button" onclick="showDiv('BraveDiv')">Brave</button>
<button role="button" onclick="showDiv('CompassionateDiv')">Compassionate</button>
<div id="BraveDiv" style="display: none;"> SOME BRAVE CONTENT HERE </div>
<div id="CompassionateDiv" style="display: none;"> SOME COMPASSIONATE CONTENT HERE </div>
function showDiv() {
document.getElementById('BraveDiv').style.display = "block";
document.getElementById('DeterminedDiv').style.display = "none";
document.getElementById('CompassionateDiv').style.display = "none";
document.getElementById('ConsiderateDiv').style.display = "none";
}
function showDiv1() {
document.getElementById('BraveDiv').style.display = "none";
document.getElementById('DeterminedDiv').style.display = "block";
document.getElementById('CompassionateDiv').style.display = "none";
document.getElementById('ConsiderateDiv').style.display = "none";
}
function showDiv2() {
document.getElementById('BraveDiv').style.display = "none";
document.getElementById('DeterminedDiv').style.display = "none";
document.getElementById('CompassionateDiv').style.display = "block";
document.getElementById('ConsiderateDiv').style.display = "none";
}
function showDiv3() {
document.getElementById('BraveDiv').style.display = "none";
document.getElementById('DeterminedDiv').style.display = "none";
document.getElementById('CompassionateDiv').style.display = "none";
document.getElementById('ConsiderateDiv').style.display = "block";
}
This might not be the sleekest way of doing it, but will get you the results you want. As each button is pressed, all others will close.
You just need to set the display style of the remaining <div>s back to none. The simplest way to do this is to first set all of them to none, then the one you want visible to block:
Note: I’ve used a function which takes the id of the target <div> as a parameter to reduce the amount of code written, but you could easily copy-paste out to separate functions if you require.
function showDiv(divName) {
// First hide all the divs
document.getElementById('BraveDiv').style.display = 'none';
document.getElementById('DeterminedDiv').style.display = 'none';
document.getElementById('CompassionateDiv').style.display = 'none';
document.getElementById('ConsiderateDiv').style.display = 'none';
// Then show the div corresponding to the button clicked
document.getElementById(divName).style.display = 'block';
}
<input type="button" value="Brave" onclick="showDiv('BraveDiv')">
<input type="button" value="Determined" onclick="showDiv('DeterminedDiv')">
<input type="button" value="Compassionate" onclick="showDiv('CompassionateDiv')">
<input type="button" value="Considerate" onclick="showDiv('ConsiderateDiv')">
<div id="BraveDiv" style="display: none">BraveDiv</div>
<div id="DeterminedDiv" style="display: none">DeterminedDiv</div>
<div id="CompassionateDiv" style="display: none">CompassionateDiv</div>
<div id="ConsiderateDiv" style="display: none">ConsiderateDiv</div>
There are alternative ways of doing this which require less code, such as this method using a little CSS and document.querySelectorAll():
function showDiv(divName) {
// First remove the selected class from all divs in output-divs
document.querySelectorAll('#output-divs > .selected').forEach(element => {
element.classList.remove('selected');
});
// Then add it to the div corresponding to the button clicked
document.getElementById(divName).classList.add('selected');
}
.output-div:not(.selected) {
display: none;
}
<input type="button" value="Brave" onclick="showDiv('brave')">
<input type="button" value="Determined" onclick="showDiv('determined')">
<input type="button" value="Compassionate" onclick="showDiv('compassionate')">
<input type="button" value="Considerate" onclick="showDiv('considerate')">
<div id="output-divs">
<div class="output-div selected" id="brave">Brave</div>
<div class="output-div" id="determined">Determined</div>
<div class="output-div" id="compassionate">Compassionate</div>
<div class="output-div" id="considerate">Considerate</div>
</div>
$(document).ready(function() {
$("#btn1").click(function(){
showDiv('div1');
});
$("#btn2").click(function(){
showDiv('div2');
});
$("#btn3").click(function(){
showDiv('div3');
});
$("#btn4").click(function(){
showDiv('div4');
});
});
function showDiv(_divId){
$(".div-class").each(function() {
if(!$(this).hasClass('div-hide'))
$(this).addClass('div-hide');
});
$('#' + _divId).removeClass('div-hide');
}
.div-class {
min-height: 50px;
border: 1px solid #eee;
margin: 10px;
padding: 10px;
width: 100%;
}
.div-hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>
<button id="btn3">Button 3</button>
<button id="btn4">Button 4</button>
<div id="div1" class='div-class div-hide'><h3>Div1 Content </h3></div>
<div id="div2" class='div-class div-hide'><h3>Div2 Content </h3></div>
<div id="div3" class='div-class div-hide'><h3>Div3 Content </h3></div>
<div id="div4" class='div-class div-hide'><h3>Div4 Content </h3></div>
My code works but I have to double click the button I clicked just to close it. I would like that when I click the other button, the opened element automatically closes.
<div class="col- menu">
<ul>
<li>Picture</li>
<li>About</li>
<li>Size</li>
</ul>
</div>
<div class="content">
<p><span id="pic1"><img src="1.jpg"></span></p>
<p><span id="description" style="display: none;">Cool!</span></p>
<p><span id="size" style="display: none;"><img src="2.jpg"></span></p>
</div>
<script type="text/javascript">
function toggleStuff(id) {
if (document.getElementById(id).style.display == 'block') {
document.getElementById(id).style.display = 'none';
} else {
document.getElementById(id).style.display = 'block';
}
}
</script>
You Can try this:
var stuffArr = ['pic1', 'description', 'size'];
function toggleStuff(id) {
stuffArr.forEach(function(currentId) {
if(currentId === id) {
document.getElementById(id).style.display = 'block';
} else {
document.getElementById(id).style.display = 'none';
}
});
}
You need to loop through all the id''s
Please note this is just demo code to give you an idea
function toggleStuff (id){
//get list of ids
var pic1 = document.getElementById ("pic1");
var size = document.getElementById ("size");
var idSize = 2;
var idArray = Array ("pic1","size");
for (var i = 0; i < idSize; i++){
if (idArray.indexOf (i) == id){
//display id
}else {
//hide id
}
}
}
One out of millions of possible solutions:
function toggleStuff(id) {
var el = document.getElementById(id)
el.classList.toggle('visible');
document.querySelectorAll('.togglable:not(#'+id+')').forEach(function(item) {
item.classList.remove('visible');
})
}
.togglable {
display: none;
}
.visible {
display: block;
}
<div class="col- menu">
<ul>
<li>Picture</li>
<li>About</li>
<li>Size</li>
</ul>
</div>
<div class="content">
<p><span id="pic1" class="togglable">PIC1</span></p>
<p><span id="description" class="togglable">DESCRIPTION</span></p>
<p><span id="size" class="togglable">SIZE</span></p>
</div>
I am trying to show images on a link click and hiding that image if clicked outside. After trying so many solutions for this I have came up with like below code.
<script>
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
</script>
<div id="wrapper" style="margin-top: -5px; text-align:center" align="center" onclick="javascript:setImageVisible('popup1', false)">
<div id="Btn7"></div>
<img id="popup1" class="img_popup1" src="../screenshots/pop-up.png" style="visibility:hidden" />
</div>
The above code is working fine. But when I add other image like below, its not working. When I clicked outside then images are not hiding.
<script>
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
$(document).click(function() {
var img1 = document.getElementById('popup1');
var img2 = document.getElementById('popup2');
img1.style.visibility = 'hidden';
img2.style.visibility = 'hidden';
});
</script>
<div id="wrapper" style="margin-top: -5px; text-align:center" align="center">
<div id="Btn7"></div>
<img id="popup1" class="img_popup1" src="../screenshots/pop-up.png" style="visibility:hidden" />
<div id="Btn8"></div>
<img id="popup2" class="img_popup2" src="../screenshots/pop-up2.png" style="visibility:hidden" />
</div>
Can anyone please suggest what should I do ?
You don't need jQuery to do this.
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
function hideAll() {
var img1 = document.getElementById('popup1');
var img2 = document.getElementById('popup2');
img1.style.visibility = 'hidden';
img2.style.visibility = 'hidden';
}
function click(e) {
e.stopImmediatePropagation();
var id, el = this;
while (el) {
el = el.nextSibling;
if (el.nodeName === 'IMG') { // finds the next sibling img element
id = el.id;
el = null;
}
}
hideAll(); // hide all images
setImageVisible(id, true); // show the right one
};
document.addEventListener('click', hideAll);
var btns = document.querySelectorAll('.btn'),
i = 0,
len = btns.length;
for (; i < len; i++) {
btns[i].addEventListener('click', click);
}
img {
width: 100px;
height: 100px;
border: 1px solid black;
}
<div id="wrapper" style="margin-top: -5px; text-align:center" align="center">
<div class="btn" id="Btn7">Image 1</div>
<img id="popup1" class="img_popup1" src="../screenshots/pop-up.png" style="visibility:hidden" />
<div class="btn" id="Btn8">Image 2</div>
<img id="popup2" class="img_popup2" src="../screenshots/pop-up2.png" style="visibility:hidden" />
</div>
Sure, as you have added a tag jquery, I am asking you to do it in a simple way like this:
Snippet:
$(function () {
$(".imgPreview").hide();
$(".unstyled li a").click(function () {
$(".imgPreview").show().find("img").attr("src", $(this).attr("href"));
return false;
});
$("body").click(function () {
$(".imgPreview").hide();
});
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none;}
body {margin: 10px;}
li {margin: 5px;}
.unstyled, .imgPreview {float: left; width: 50%;}
.unstyled, .imgPreview img {max-width: 100%;}
p {margin: 5px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>Click on a link to show the respective image. Click outside to hide it!</p>
<p>Also you can right click and open it to open the image in a new tab!</p>
<ul class="unstyled">
<li>350x150</li>
<li>750x150</li>
<li>350x150</li>
<li>100x100</li>
<li>350x150</li>
</ul>
<div class="imgPreview">
<img src="" alt="" />
</div>
Try this simple demo
<!DOCTYPE html>
<html>
<head>
<script src = "jquery-1.10.2.min.js"></script>
</head>
<body>
Click to show image
<img id="image" style="display:none;height:500px; width:500px;">
<script type="text/javascript">
$('#imageLink').click(function (e){
e.stopPropagation();
$('#image').show();
});
$('body').click(function () {
$('#image').hide();
})
</script>
</body>
</html>
Remove inline event handler and write for common click event ,
1) bind the click event for all a tag inside wrapper id and then show the images when link is clicked
2) bind the click event for document and hide the all images when clicking outside of link
$("#popup1,#popup2").hide();
$("#Btn7,#Btn8").click(function (e) {
e.stopPropagation();
$(this).next().show();
})
$(document).click(function () {
$("#popup1,#popup2").hide();
})
DEMO
$(document).ready(function () {
$("#linkbutton_id").click(function () {
alert("The paragraph was clicked.");
if($("#image").hide())
{
$("#image").show();
return false;
}
});
});
$(document).ready(function () {
$("#div_id").click(function(){
$("#image").hide();
});
});
Code plus output link
https://jsfiddle.net/umxrn0Lg/2/
fullscreen output link
https://jsfiddle.net/umxrn0Lg/3/embedded/result/
I'm basically trying to make open menu close when user click anywhere. im new and i dont know what is problem. so far i am using this code, here is my html, css and javaScript. i think problem is in my JavaScript.
thanks for help.
HTML
<div class="menu-button" style="width:23px; cursor: pointer;" onClick="show_menu()"><span style="color:#b0acac;">▼</span></div>
<div id="dropdown_menu" class="hidden_menu">
<ul id="container">
<li>Settings<br></li>
<li>Log Out</li>
</ul>
</div>
CSS
.menu-button{
position: relative;
left:1556px;
top:-43px;
}
.hidden_menu{
display:none
}
#dropdown_menu ul li {
text-decoration:none;
display: inline;
cursor: pointer;
position: relative;
left:-20px;
top:2px;
}
#dropdown_menu ul{
width:80px;
height:90px;
background-color:#efefef;
position:relative;
top:-64px;
left:1460px;
border-color:#ff0000;
border-width:2px;
}
JavaScript
<script>
function show_menu(){
var menu = document.getElementById('dropdown_menu');
if(menu.style.display == 'block'){
menu.style.display = 'none';
}else {
menu.style.display = 'block';
}
}
function hide_menu(){
var menu = document.getElementById('dropdown_menu');
if(menu.style.display == 'none'){
menu.style.display = 'block';
}
}
var cl = document.getElementById("body");
cl.addEventListener("click", hide_menu);
</script>
This can help you.
HTML Code
<div class="menu-button" style="width:23px; cursor: pointer;" ><span id="button" style="color:#b0acac;">Show Menu</span></div>
<div id="dropdown_menu" class="hidden_menu">
<ul id="container">
<li>Settings<br></li>
<li>Log Out</li>
</ul>
</div>
Css
.hidden_menu { display:none;}
JavaScript Code
var dropMenu = document.getElementById('dropdown_menu'),
menuButton = document.getElementById('button'),
dropUL = document.getElementById('container').childNodes;
function hide_menu(evt){
evt = evt || window.event; // get window.event if evt is falsy (IE)
var targetElement = evt.target || evt.srcElement; // get srcElement if target is falsy (IE)
if(targetElement === menuButton || targetElement.nodeName.toLowerCase() === 'li' ){
dropMenu.style.display = 'block'
} else {
dropMenu.style.display = 'none'
}
}
// For legacy broser(IE8 and IE7) support
function addEvent(el, type, fn){
if(typeof addEventListener !== 'undefined'){
el.addEventListener(type, fn, false)
} else {
el.attachEvent('on'+type, fn);
}
}
addEvent(document, 'click', hide_menu);
Demo
If you want plain js:
document.addEventListener('click', function(e){
console.log(e.target.id)
if(e.target.id!=="dropdown_menu")
console.log("document Clicked");
});
It is same as above function but written in javascript
Try
function hide_menu(e){
var menu = document.getElementById('dropdown_menu');
if(e.target != menu) {
menu.style.display = 'none';
}
}
document.body.addEventListener("click", hide_menu);
$('body').click(function(){
if($(this).attr('id')!='dropdown_menu' && !$(this).hasClass('menu-button'))
// code to close the menu
});
Making sure that the click is not on the div for menu