I am trying to create a toggle function with JavaScript (not jQuery).
I have created an ID named box, and a class within the ID named box-open.
The width of the ID box is 100px.
The width of box-open is set to 1000px.
When I try to use my code I get this error, that displays “Cannot set property 'display' of undefined”.
I have tried writing the code a couple of different ways, but I always seem to get the same error in the console.
function toggle(open) {
box = document.getElementById('box').style.display = 'block';
if (open == true) {
box.style.display = 'none';
boxOpen = document.getElementsByClassName('box-open').style.display = 'block';
} else {
box.style.display = 'block';
boxOpen.style.display = 'none';
}
}
#box {
width: 100px;
height: 100px;
background: gold;
text-align: center;
display: block;
}
.box-open {
width: 50px;
height: 50px;
background: green;
display: none;
}
<div id="box" class="box-close"></div>
<button type="button" onClick="toggle()">click me</button>
This is a link to my codepen, where you can find the code
http://codepen.io/2bu/pen/YNYjjR
I am not sure but this line:
box = document.getElementById('box').style.display = 'block'
should be maybe
box = document.getElementById('box');
Your function is not very flexible because it can only toggle a specific box with ID "box". Instead you could pass in a selector for the element you want to toggle:
<div id="box" class="box-close"></div>
<button type="button" onClick="toggle('#box')">click me</button>
And then in your Javascript:
function toggle(selector) {
var box = document.querySelector(selector);
var isOpen = box.style.display === "block";
box.style.display = isOpen ? "none" : "block";
}
This way you can use the same toggle function to toggle any box you like.
Here is a simple jQuery implementation. Just change the .box-toggled class to be whatever you actually want. It also uses eventListener to keep your HTML cleaner.
https://jsfiddle.net/segbxnh3/3/
var box = document.querySelector('#box');
var toggleButton = document.querySelector('button');
toggleButton.addEventListener('click', function() {
$(box).toggleClass('box-toggled');
});
UPDATE:
Here is a vanilla JS implementation.
https://jsfiddle.net/segbxnh3/5/
var box = document.querySelector('#box');
var toggleButton = document.querySelector('button');
toggleButton.addEventListener('click', function() {
if (box.classList.contains('box-toggled')) {
box.classList.remove('box-toggled');
} else {
box.classList.add('box-toggled');
}
});
You can use like this.
function toggle(open, element){
box = document.getElementById('box');
boxOpen = document.getElementById('box-open');
if ( open == true) {
box.style.display = 'none';
boxOpen.style.display = 'block';
element.setAttribute('onclick', "toggle(false, this);");
}else{
box.style.display = 'block';
boxOpen.style.display = 'none';
element.setAttribute('onclick', "toggle(true, this);");
}
}
*{
margin:0px;
padding:0px;
font-family: 'Montserrat', sans-serif;
}
#box{
width:100px;
height: 100px;
background: gold;
text-align: center;
display:block;
}
#box-open{
width:50px;
height: 50px;
background: green;
display: none;
}
<div id="box"></div>
<div id="box-open"></div>
<button type="button" onClick="toggle(true, this);" >click me </button>
Also, check this solution
Related
I'm new to coding, but looking at doing a bootcamp to help me learn some more, however, at the moment I am having some trouble getting some code to do what I need it to.
The following code is what I use on the website I'm working on:
<button class="zerobut" onclick="myFunction5()">Open</button>
<script>
function myFunction5() {
var x = document.getElementById("product5");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
What I need is an automatic hide once a different button is clicked. There are 5 different categories from which a customer must choose before the options are displayed, but at the moment it doesn't close the previous option unless you click on the button again.
Is anyone able to help me understand what I need to change to make this happen? (sorry if I'm explaining this poorly.)
Here's another section's code. So when this one opens, the first one should close automatically if possible.
`
<button class="healthbut" onclick="myFunction3()">Open2</button>
<script>
function myFunction3() {
var x = document.getElementById("product3");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
`
It doesn't work the first time because the style.display attribute is initially set to the empty string. If you add the style attribute it works.
function myFunction5() {
var x = document.getElementById("product5");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
.products {
background-color:yellow;
border: 1px solid black;
padding:1rem;
}
<button class="zerobut" onclick="myFunction5()">Open/Close</button>
<div class = 'products' style='display:block' id='product5'>Product 5 panel</div>
A better option is to just check to see if your style.display attribute is not 'none' and change it otherwise as below
function myFunction5() {
var x = document.getElementById("product5");
if (x.style.display !== "none") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
.products {
background-color: yellow;
border: 1px solid black;
padding: 1rem;
}
<button class="zerobut" onclick="myFunction5()">Open/Close</button>
<div class='products' id='product5'>Product 5 panel</div>
Finally, an even better way to do it is to create a 'hide' class and toggle the class element
function myFunction5() {
var x = document.getElementById("product5");
x.classList.toggle('hide');
}
.products {
background-color:yellow;
border: 1px solid black;
padding:1rem;
}
.products.hide {
display: none;
}
<button class="zerobut" onclick="myFunction5()">Open/Close</button>
<div class = 'products' id='product5'>Product 5 panel</div>
Finally, if you've got some panels you need to hide when you're displaying others, then this can be done as follows:
productNumber = 1;
totalNumberOfProducts = 5;
function myFunction5() {
//Select all elements with the class 'products'.
const elements = document.querySelectorAll(".products");
//choose the next element to display
productNumber++;
//If we get past the last element then go back to the one with id 'product1'
if (productNumber > totalNumberOfProducts) {
productNumber = 1;
}
//Loop through each element and hide all elements except the one that's got the id of
//"product"+productNumber;
elements.forEach((element) => {
const elementId = element.getAttribute('id');
if (elementId == 'product' + productNumber) {
element.classList.remove('hide');
} else {
element.classList.add('hide');
}
});
}
.products {
border: 1px solid black;
padding: 1rem;
}
#product1 {
background-color: brown;
}
#product2 {
background-color: salmon;
}
#product3 {
background-color: pink;
}
#product4 {
background-color: skyblue;
}
#product5 {
background-color: yellow;
}
.products.hide {
display: none;
}
<button class="zerobut" onclick="myFunction5()">Go to next panel</button>
<div class='products' id='product1'>Product 1 panel</div>
<div class='products hide' id='product2'>Product 2 panel</div>
<div class='products hide' id='product3'>Product 3 panel</div>
<div class='products hide' id='product4'>Product 4 panel</div>
<div class='products hide' id='product5'>Product 5 panel</div>
I created a simple function which shows or hides a div tag on clicking a button but how can i set it to initially be hiding and after clicking the button it is displayed?
Just set it's display style property to None.
element = document.getElementById('toggle');
button = document.getElementById('toggle-button');
function hideAndShow(){
if(element.style.display == 'none'|| element.style.display == '') // checks if the display property is set to none or not
{
element.style.display = 'Block'; // if set to none then set the display property to block
button.innerHTML = 'Hide'; // changes the button's text
}
else{
element.style.display = 'None'; // otherwise set it to none
button.innerHTML = 'Show';
}
}
#toggle{
width: 100%;
margin: auto;
height: 50px;
display: None; /*this set's the divison to a hidden state by default*/
background-color: rgba(248,25,34,0.8);
}
#toggle-button{
width: 100%;
margin: 5px;
height: 25px;
padding: 5px;
color: rgba(25,25,67,0.5);
}
<div id='toggle'></div>
<button id='toggle-button' onclick='hideAndShow()'>Show</button>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
};
function toggle() {
document.getElementById('test').style.display = 'block';
}
.hide {
display: none;
}
<div id="test" class="hide">Test</div>
<button onclick="toggle()">Toggle</button>
function btnClick(){
const divElement = document.getElementById('myDiv');
if (divElement.classList.contains("show")) {
divElement.classList.remove("show")
divElement.classList.add("hide")
} else {
divElement.classList.add("show")
divElement.classList.remove("hide")
}
}
.hide{
display: none
}
.show{
display: block
}
<div id="myDiv" class="hide">
Hello, I am Div HTML Content
</div>
<button onclick="btnClick()">Click Me!!</button>
In my HTML i have put a script and a div. Now i want to make 3 buttons next to each other in the while block in the middle of the page. I want to make the 3 buttons without changing the html and thus make it dynamic inside the javascript.
So far i have put a var in the javascript but i do not know what to do now..
I earlier made a html page with a button element inside it and then change all of it using the html but i cant figure out how to do this if there isn't a button element inside the html page.
HTML:
<body>
<div id="container"></div>
<script src="button.js"></script>
</body>
CSS:
html{
background-color: grey;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 450px;
background-color: white;
position: relative;
}
JS:
var buttons = document.getElementsById("container");
button.onclick = onbuttonclicked;
function onbuttonclicked(){
if (onbuttonclicked) {
button1.style.backgroundColor = "red";
button1.disabled=true;
} else {
button1.style.backgroundColor = "green";
button1.disabled=false;
}
}
so like here each button has its own text and color
Create the buttons and append them as children of your buttons container. Here I am creating one button. You can do the same for other buttons:
var buttons = document.getElementById("container");
var button1 = document.createElement("button");
button1.onclick = onbuttonclicked;
buttons.appendChild(button1);
function onbuttonclicked() {
if (onbuttonclicked) {
button1.style.backgroundColor = "red";
button1.disabled = true;
} else {
button1.style.backgroundColor = "green";
button1.disabled = false;
}
}
Note that onbuttonclicked will always evaluate to true because you are checking whether the function is defined or not. Also, if you want to change the background and disabled attribute of the clicked button, rather than button1 explicitly, you should use this instead of button1.
var container = document.querySelector("#container");
var arr = ['success','danger','warning'];
for (var i = 0; i < 3; i++) {
var button = document.createElement("button");
button.setAttribute("attribute", arr[i]);
button.innerHTML = arr[i];
button.className += arr[i];
container.appendChild(button);
console.log(button)
}
html{
background-color: grey;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 450px;
background-color: white;
position: relative;
}
btn {
border: none;
background-color: inherit;
padding: 14px 28px;
font-size: 16px;
cursor: pointer;
display: inline-block;
}
.success {
color: black;
background:green;
}
.success:hover {
background-color: #4CAF50;
color: white;
}
.warning {
background: yellow;
color:black;
}
.warning:hover {
background: #ff9800;
color: white;
}
.danger {
background: red;
color:black;
}
.danger:hover {
background: #f44336;
color: white;
}
<body>
<div id="container"></div>
<script src="button.js"></script>
</body>
I think like this?
So for this you are trying to manipulate the DOM using JavaScript, take your div#container and you are trying to append three button elements. The process for doing this (or really any HTML Element with JS DOM manipulation is fairly similar, you create the element, add the attributes you want, and then "append" it to the main element where you want it inserted)
Check out my example below to add 3 buttons to your <div id="container">:
var container = document.querySelector("#container"); //or use document.getElementById("container"), makes no difference
for (var i = 0; i < 3; i++) {
var button = document.createElement("button"); //works with any HTML5 element
button.setAttribute("attribute", "value"); //Use this to add attributes such as id, class, styles, or even event listeners like onclick
button.innerHTML = "Button Text"; //Make sure to add button text if you don't want an empty button!!
container.appendChild(button);
}
Since you said you want the buttons next to each other (I'm assuming this means side-by-side) then you can add a style to your CSS
button {
display: inline;
}
but of course that would depend on your usage, meaning if you wanted all buttons to be inline. If you wanted just those three then you can use the .setAttribute("class", "classname"); to add a class and then define that class to have the same style.
You can also make your container a CSS flexbox and have each of the buttons aligned horizontally
#container {
display: flexbox;
flex-direction: row; /*Use row for horizontal, column for vertical*/
}
and you wouldn't need to style your buttons. But the choice is yours.
Edit: to make 2 buttons, one green and one red,
//Make a green text button1
var button1 = document.createElement("button"); //works with any HTML5 element
button1.style.color = "green";
button1.innerHTML = "Button1 Text"; //Make sure to add button text if you don't want an empty button!!
container.appendChild(button1);
//Make a red text button2
var button2 = document.createElement("button"); //works with any HTML5 element
button2.style.color = "red";
button2.innerHTML = "Button2 Text"; //Make sure to add button text if you don't want an empty button!!
container.appendChild(button2);
If you wanted to change the background colors as well you could add button.style.backgroundColor = "pink" or whatever color you'd like
Check out: JavaScript DOM Methods, this was a REAL help to me when I was learning what you're trying to do right now!
To give the buttons a function use the onclick value of the button, so in the above script we can add something like this:
button1.onclick = button1AfterClicked;
//Or
button1.setAttribute("onclick", "button1AfterClicked");
And since JavaScript is pretty lenient we can define our button1AfterClicked() anywhere
function button1AfterClicked() {
button1.style.color = "some color";
//And so forth...
}
For these kinds of questions I highly suggest looking up the answer on google because I know W3Schools does a splendid job on explaining the basics and more: OnClick Event JavaScript
You Can do it with jquery check is this right ?
$("#container").html('<button class="green-button">Button1</button><button class="red-button">Button2</button><button class="yellow-button">Button3</button>');
$( ".red-button" ).click(function() {
$(".red-button").css("background-color", "red");
});
$( ".green-button" ).click(function() {
$(".green-button").css("background-color", "green");
});
$( ".yellow-button" ).click(function() {
$(".yellow-button").css("background-color", "yellow");
});
<div id="container"></div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
Following is what might help you,you can set margin and padding to your needs:
var button = document.createElement("button");
button.innerHTML = "Do Something";
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener ("click", function() {
alert("did something");
});
The code provided is all you needed for your current project
You can add the style of the button in CSS
// container of buttons
const containerBtn = document.querySelector('.container');
let createBtns = (classParam, text) => {
let btn = document.createElement('button');
btn.classList.add(classParam);
btn.innerText = text;
containerBtn.append(btn);
return btn;
};
// 1. add the button **class**
// 2. add the button text
let btn1 = createBtns('btn-1', 'test');
// add event listener to btn1
btn1.addEventListener('click', () => {
console.log(1);
});
This is an example where three buttons are created and styled with CSS. They use the nth-of-type() and attribute selectors to style the buttons based on their position and disabled state.
Do note that when disabling the buttons they won't listen to the click event anymore.
const container = document.getElementById('container');
for (let i = 0; i < 3; i++) {
const button = document.createElement('button');
button.textContent = `Button ${i + 1}`;
container.append(button);
}
container.addEventListener('click', event => {
const { target } = event;
if (!target.tagName.toLowerCase() === 'button') {
return;
}
if (!target.disabled) {
target.disabled = true;
} else {
target.disabled = false;
}
});
#container {
display: flex;
}
#container button {
padding: 15px;
color: white;
}
#container button:first-of-type {
background-color: red;
}
#container button:nth-of-type(2) {
background-color: blue;
}
#container button:last-of-type {
background-color: goldenrod;
}
#container button[disabled] {
background-color: black;
}
<div id="container"></div>
I want to make a popup that should appear once a button is clicked and disappear once the user clicks outside of the box.
I'm not sure how to make the div disappear when I click outside of it.
var popbox = document.getElementById("popbox");
document.getElementById("linkbox").onclick = function () {
popbox.style.display = "block";
};
???.onclick = function () {
popbox.style.display = "none";
};
Here is the second version which has a transparent overlay as asked by the asker in the comments...
window.onload = function(){
var popup = document.getElementById('popup');
var overlay = document.getElementById('backgroundOverlay');
var openButton = document.getElementById('openOverlay');
document.onclick = function(e){
if(e.target.id == 'backgroundOverlay'){
popup.style.display = 'none';
overlay.style.display = 'none';
}
if(e.target === openButton){
popup.style.display = 'block';
overlay.style.display = 'block';
}
};
};
#backgroundOverlay{
background-color:transparent;
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
display:block;
}
#popup{
background-color:#fff;
border:1px solid #000;
width:80vw;
height:80vh;
position:absolute;
margin-left:10vw;
margin-right:10vw;
margin-top:10vh;
margin-bottom:10vh;
z-index:500;
}
<div id="popup">This is some text.<input type="button" id="theButton" value="This is a button"></div>
<div id="backgroundOverlay"></div>
<input type="button" id="openOverlay" value="open popup">
Here is the first version...
Here is some code. If there is anything else to add, please let me know :)
The event (e) object gives access to information about the event. e.target gives you the element that triggered the event.
window.onload = function(){
var divToHide = document.getElementById('divToHide');
document.onclick = function(e){
if(e.target.id !== 'divToHide'){
//element clicked wasn't the div; hide the div
divToHide.style.display = 'none';
}
};
};
<div id="divToHide">Click outside of this div to hide it.</div>
Here, the idea is to detect click events on the page and set the container’s display to none only when the target of the click isn’t one of the div descendants.
HTML
<div id="container">
<label>Enter your name:</label>
<input type="text">
<button id="submit">Submit</button>
</div>
JS
document.addEventListener('mouseup', function(e) {
var container = document.getElementById('container');
if (!container.contains(e.target)) {
container.style.display = 'none';
}
});
This is code I use to close my side bar when click outside
function openNav() {
document.getElementById("mySidebar").style.width = "100px";
document.getElementById("curtain_menu").style.marginLeft = "100px";
}
function closeNav() {
document.getElementById("mySidebar").style.width = "0";
document.getElementById("curtain_menu").style.marginLeft = "0";
}
document.onclick = function (e) {
if (e.target.id !== 'mySidebar' && e.target.id !== 'btn_frontpage_menu') {
if (e.target.offsetParent && e.target.offsetParent.id !== 'mySidebar')
closeNav()
}
}
.sidebar {
font-family: sans-serif;
height: 50%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
opacity: 0.9;
}
.sidebar a,
.dropdown-btn {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 1vw !important;
color: rgb(195, 195, 195);
display: block;
background: none;
width: 100%;
text-align: left;
cursor: pointer;
outline: none;
transition: 0.3s;
border: none;
}
.dropdown-container a {
color: rgb(174, 174, 174) !important;
}
.sidebar a:hover,
.dropdown-btn:hover,
.dropdown-container a:hover {
color: green !important;
/* background-color: #5c5c5c; */
}
.sidebar .closebtn {
position: absolute;
top: 12px;
font-size: 36px !important;
margin-right: 5px;
text-align: right;
right: 20px;
}
.openbtn {
font-size: 20px !important;
cursor: pointer;
background-color: transparent;
color: black;
padding: 6px 15px;
border: none;
float: left;
}
#main {
position :absolute;
width: 100%;
height: 100%;
left: 100px
}
<div id="mySidebar" class="sidebar" style="width: 100px;">
<a href="javascript:void(0)" class="closebtn"
onclick="closeNav()">×</a>
Home
<div class="dropdown-container">
Job Management
Request
Pending
</div>
</div>
<div id="curtain_menu">
<button id="btn_frontpage_menu" class="openbtn" onclick="openNav()">☰</button>
<div id="datetime"></div>
</div>
<div id="main"> Outside of 'Side Bar' is here
</div>
Here is my Solution.
yourFunc=e=>{
var popbox = document.getElementById("popbox");
if(e.target.id !=="popbox"){
popbox.style.display = "none";
}else{
popbox.style.display = "block";
}
}
document.addEventListener("click",yourFunc)
hope this will work for you
<script>
// Get the element
var modal = document.getElementById('modal');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
This code is tested and it's working nicely, thank you.
Could be done with onblur event.
// required for focus
divEl.setAttribute('tabindex', '1');
divEl.onblur = event => {
// hide only if blur occurred outside divEl, ignore its children
if (!event.currentTarget.contains(event.relatedTarget)) {
hide();
}
// re-focus, if a child took it
divEl.focus();
};
divEl.focus();
P.S. For IE11 a small hack event.relatedTarget = event.relatedTarget || document.activeElement; could be required.
<div class='icon alk-icon-close'>hidden hire</div>
document.addEventListener('click', function(e) {
var target = e.target.classList.value
if (target == 'icon alk-icon-close') ) {
hidden hire
}
});
plug this in
(function(){
// click outside of element to hide it
let hels = [];
window.hidable = (el, excepter, hider) => {
// hider takes el as the only arg
hels.push([el, excepter, hider]);
return el;
}
window.addEventListener('click', e=>{
for(let i = 0; i < hels.length; i++){
let el = hels[i][0];
let excepter = hels[i][1];
let hider = hels[i][2];
if(!el.contains(e.target) && excepter !== e.target){
hider(el);
}
}
});
})()
unit test
/* excepter is the element to trigger panel show */
// example implementation
window.hidable(panel_el, show_panel_button, el=>el.remove());
// other hiders can be:
el=>el.style.display = 'none';
// depends on your show implementation
el.onmouseleave = function(){
document.body.onclick = function(){
el.style.display = 'none';
document.body.onclick = null;
}
}
Okay, here's a jQuery based solution based on any div clicked within the DOM.
$('div').on('click', function(e){
var parents = $(e.currentTarget).parents();
for (var i = 0; i < parents.length; i++) {
if (parents[i].id === 'divToHide' || e.currentTarget.id === 'divToHide') {
// you are in the popup
};
}
e.stopPropagation();
});
This looks at your current element, as well as any of the parents, and checks if the id matches up. If divToHide is in the parents() list, then you keep the popup open.
*NOTE: This requires wrapping your content within a wrapper div or something similar.
My aim of the code which you'll find below is to make some kind of a filter. But for some reason it won't work.
As you can see when you try to hide the boxes when selecting the input box it won't work; but when you make var x, var x = document.getElementById("a"); it will work. Is there a way to hide all the different boxes?
function myFunction1() {
var x = [document.getElementById("a"), document.getElementById("b"), document.getElementById("c")];
if (x.style.display == 'block')
x.style.display = 'none';
else
x.style.display = 'block';
}
#a, #b, #c {
float: left;
width: 25%;
height: 200px;
background-color: #ffffff;
border: 1px solid #002261;
margin: -1px;
text-align: center;
display: block;
}
<input type="checkbox" onclick="myFunction1()">Try to hide all
<div id="a">item a</div>
<div id="b">item b</div>
<div id="c">item c</div>
As you can see you can't hide all the boxes simultaneously.
You are making a list([]) and then trying to style the list itself, not its contents.
JavaScript provides an easy list method for this, forEach():
function myFunction1() {
var x = [document.getElementById("a"), document.getElementById("b"), document.getElementById("c")];
x.forEach(function(item) {
if (window.getComputedStyle(item).display === 'block') item.style.display = 'none';
else item.style.display = 'block';
});
}
See this codepen demo
Note: your code had a minor bug in getting the style, item.style.display only gets inline styles, so the first time you call the function it will not hide the element. I fixed it in the above code and codepen with window.getComputedStyle(item).display.