Hide div class when click outside - javascript

function nav_category_show() {
var x = document.getElementById("nav_dropdown_items");
if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show";
}
else {
x.className = x.className.replace(" w3-show", "");
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<span onclick="nav_category_show()">click here<i class="fa fa-bars"></i></span>
<div id="nav_dropdown_items" class="w3-animate-zoom w3-dropdown-content w3-bar-block w3-card-4">
Link 1
</div>
I want to hide this #nav_dropdown_items when click on outside of the div.How should I do it? Thank you!

After adding class in the nav_category_show function stop the event propagation using event.stopPropagation.
Add another event to the body and in that remove the class from nav_category_show
function nav_category_show(e) {
var x = document.getElementById("nav_dropdown_items");
if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show";
} else {
x.className = x.className.replace("w3-show", "");
}
e.stopPropagation();
}
document.body.addEventListener('click', function() {
document.getElementById("nav_dropdown_items").classList.remove('w3-show');
})
body {
width: 500px;
height: 500px;
border: 1px solid red;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<span onclick="nav_category_show(event)">click here<i class="fa fa-bars"></i></span>
<div id="nav_dropdown_items" class="w3-animate-zoom w3-dropdown-content w3-bar-block w3-card-4">
Link 1
</div>

Since you're already referencing jquery, you can use it to easily hide / show the div of choice:
var target = $("#nav_dropdown_items");
if(target.hasClass("w3-show")) {
target.hide(); // hides it
target.removeClass("w3-show");
}
else {
target.show(); //shows it
target.addClass("w3-show");
}

Related

Transform icon to a button with Js

am trying to make this icon as button but it doesn't work
//icons buttons
let bookmark='<a id="bookmarkbutton"><i id="bookmark" class="fas fa-bookmark fa-3x"></i></a>';
let bookmarkbutton= document.getElementById("bookmarkbutton");
//bookmark on click function
bookmarkbutton.onclick=function() {
console.log("the button works");
}
here is the link to repository https://github.com/yaminecy/html
You have to first insert the "button" into the DOM. Then you can select it.
let bookmark = '<a id="bookmarkbutton"><i id="bookmark" class="fas fa-bookmark fa-3x"></i></a>';
document.body.innerHTML+=bookmark;
let bookmarkbutton = document.getElementById("bookmarkbutton");
bookmarkbutton.onclick = function() {
console.log("the button works");
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
just use jquery
$(document).append($('<a id="bookmarkbutton"><i id="bookmark" class="fas fa-bookmark fa-3x"></i></a>'););
$('#bookmarkbutton').off('click');
$('#bookmarkbutton').on('click', (event)=>{
console.log("the button works");
});
In addition to having to enter the html before using onclick, I suggest you use:
addEventListener instead of onclick
cursor:pointer; css, so you can simulate button
//icons buttons
let bookmark = '<a id="bookmarkbutton"><i id="bookmark" class="fas fa-bookmark fa-3x"></i></a>';
document.body.innerHTML += bookmark;
let bookmarkbutton = document.getElementById("bookmarkbutton");
//bookmark on click function
bookmarkbutton.addEventListener('click', () => {
console.log("the button works");
});
i {
cursor: pointer;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

Saving a toggled class Div (with local storage)

So I have an example of a basic classtoggle with a div but can I make it so the "active class" can stay switched with a refresh/re-open. Could this be done?
function myfunc(div) {
var className = div.getAttribute("class");
if(className=="normal") {
div.className = "active";
}
else{
div.className = "normal";
}
}
.normal /*Default*/
{width:25%; height:25%; background: #ffeb00;}
.active /*Switch*/
{width:25%; height:25%; background: #ff00e2;}
<html>
<head>
<title>Test</title>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>
<body>
<div id="div" class="normal" onclick="myfunc(this)"></div>
<script src=".jquery-3.2.1.min.js"></script>
<script src="script.js"></script>
</body>
</html>
Thank You for all future Answers.
Use the localStorage to hold the last class
try jsfiddle
$("#div").addClass(localStorage.getItem('ClassName')) ;
$("#div").on("click",function(){
if($(this).hasClass('active')){
$(this).removeClass("active").addClass("normal");
localStorage.setItem('ClassName', 'normal');
}
else{
$(this).removeClass("normal").addClass("active");
localStorage.setItem('ClassName', 'active');
}
});
Something similar to this, haven't tested but this will get you on the right track (note that snippet cannot run on stack overflow due to being sandboxed)
function localStorageExists() {
if (typeof(Storage) !== "undefined") {
return true;
}
return false;
}
if (localStorageExists()) {
myfunc(document.getElementById('div'));
}
function myfunc(div) {
var className = div.getAttribute("class");
if (className == "normal" || (localStorageExists() && localStorage.getItem('someKey') == 'active')) {
div.className = "active";
localStorage.setItem('someKey', 'active');
} else if (className == "active" || (localStorageExists() && localStorage.getItem('someKey') == 'normal')) {
div.className = "normal";
localStorage.setItem('someKey', 'normal');
}
}
.normal
/*Default*/
{
width: 25%;
height: 25%;
background: #ffeb00;
}
.active
/*Switch*/
{
width: 25%;
height: 25%;
background: #ff00e2;
}
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="div" class="normal" onclick="myfunc(this)"></div>
<script src=".jquery-3.2.1.min.js"></script>
<script src="script.js"></script>
</body>
</html>

Jquery - hover changes to click after several resizes

I am trying to build a basic tab-navigation. When I hover about a tab (step), then the background of the tab gets green.
But after several hovers/resizes of the browser, hover doesnt't work anymore. Then I have to click on the tab in order to get the green background. It kind of freezes.
Thats the jsFiddle:
https://jsfiddle.net/rob_the_mob_87/L84kyym1/
Here is my minimal code:
index.html
<html>
<head>
<title>Tabs</title>
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script type="text/javascript" src="js/static.js">
</script>
<link rel="stylesheet" type="text/css" href="./css/main.css">
</head>
<body>
<div class="process_step active" id="1">Step 1</div>
<div class="process_step" id="2">Step 2</div>
</body>
</html>
main.css
.process_step{
}
.active{
background-color: green;
}
static.js
$(document).ready(function () {
bindShowStepHandlers()
});
this.bindShowStepHandlers = function () {
$('.process_step').each(function() {
$(this).hover(function () {
var clickedStepId = $(this).attr('id');
openStep(clickedStepId);
});
});
}
this.openStep = function (clickedStepId) {
$('.process_step').each(function() {
var stepId = $(this).attr('id');
if (stepId == clickedStepId) {
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
}
check this snippet below. i think it is what you want..
$(document).ready(function() {
bindShowStepHandlers()
});
this.bindShowStepHandlers = function() {
$('.process_step').each(function() {
$(this).on('mouseenter',function() {
$(this).addClass('active');
});
$(this).on('mouseleave',function() {
$(this).removeClass('active');
});
});
}
.process_step {}
.active {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="process_step active" id="1">Step 1</div>
<div class="process_step" id="2">Step 2</div>

Accessing Dynamically created elements and id in javascript

I am learning javascript and trying to do this with pure javascript..
I have created an input which when user fill and click on "Add Input Text" it will wrap the text into li tags and also add close button on the each input and add the input content to the div under it, I am using following code..
I am unable to make the close button work which are on the right side of each list items...
Please help.. Thanks
var inputBox = document.getElementById('input-box');
var inputDisplay = document.getElementById('input-display');
function clickme(){
if(inputDisplay.value == ""){
alert("please put something in the input field.");
}else
inputBox.innerHTML += "<li>" + inputDisplay.value + 'x</li>';
}
function clearInput(){
inputBox.innerHTML = "";
}
function delLast(){
if( inputBox.innerHTML === "") {
alert("There is nothing to delete");
}else{
var lastInputText = inputBox.lastChild;
lastInputText.remove();
}
}
var closeThis = document.getElementById("closebtn");
closeThis.addEventListener('click' , function(){
this.parentNode.remove();
});
.container{min-height:400px;width:100%;background-color:#999;color:#fff;float:left}.input-container{padding:10px;background-color:#777;-moz-border-radius:10px;-webkit-border-radius:10px;border-radius:10px}a#closebtn{background-color:#8B8B8B;float:right;padding:1px 3px;margin:0px;color:#fff;text-decoration:none}#input-box{list-style-type:none}#input-box li{color:#FFF;background-color:#404040;padding:5px;width:300px;margin:0px;float:left;clear:both;margin-bottom:10px;-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript-learning</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<div class="input-container">
<input type="text" id="input-display">
<button onclick = "clickme()">Add input text</button>
<button onclick= "clearInput()">clear Input Box</button>
<button onclick= "delLast()">Del Last</button>
</div> <!--input-container -->
<div id ="main-content-container">
<ul id= "input-box">
</ul>
</div> <!--input-box -->
<div class="array-div">
</div>
</div> <!-- container -->
<!-- javascripts -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/underscore/underscore.min.js"></script>
<script src="bower_components/backbone/backbone-min"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
you need to add a onclick event on your x link and pass the element as parameter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript-learning</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<div class="input-container">
<input type="text" id="input-display">
<button onclick = "clickme()">Add input text</button>
<button onclick= "clearInput()">clear Input Box</button>
<button onclick= "delLast()">Del Last</button>
</div> <!--input-container -->
<div id ="main-content-container">
<ul id= "input-box">
</ul>
</div> <!--input-box -->
<div class="array-div">
</div>
</div> <!-- container -->
<!-- javascripts -->
<script>
var inputBox = document.getElementById('input-box');
var inputDisplay = document.getElementById('input-display');
function clickme(){
if(inputDisplay.value == ""){
alert("please put something in the input field.");
}else
inputBox.innerHTML += "<li>" + inputDisplay.value + 'x</li>';
}
function clearInput(){
inputBox.innerHTML = "";
}
function delLast(){
if( inputBox.innerHTML === "") {
alert("There is nothing to delete");
}else{
var lastInputText = inputBox.lastChild;
lastInputText.remove();
}
}
var closeThis = document.getElementById("closebtn");
closeThis.addEventListener('click' , function(){
this.parentNode.remove();
});
function close_click(elem)
{
elem.parentNode.remove();
}
</script>
</body>
</html>
i added close_click function in javascript that is being called in every of your created close button.
Change closebtn from an id to a class, because ids must be unique.
You can then replace the closebtn click handler with a delegated event on document.body:
document.body.addEventListener('click', function(event) {
if(event.target.className==='closebtn') {
event.target.parentNode.remove();
}
});
event.target will be the element that has been clicked.
Snippet
var inputBox = document.getElementById('input-box');
var inputDisplay = document.getElementById('input-display');
function clickme(){
if(inputDisplay.value == ""){
alert("please put something in the input field.");
}else
inputBox.innerHTML += "<li>" + inputDisplay.value + 'x</li>';
}
function clearInput(){
inputBox.innerHTML = "";
}
function delLast(){
if( inputBox.innerHTML === "") {
alert("There is nothing to delete");
}else{
var lastInputText = inputBox.lastChild;
lastInputText.remove();
}
}
document.body.addEventListener('click', function(event) {
if(event.target.className==='closebtn') {
event.target.parentNode.remove();
}
});
.container{min-height:400px;width:100%;background-color:#999;color:#fff;float:left}.input-container{padding:10px;background-color:#777;-moz-border-radius:10px;-webkit-border-radius:10px;border-radius:10px}a.closebtn{background-color:#8B8B8B;float:right;padding:1px 3px;margin:0px;color:#fff;text-decoration:none}#input-box{list-style-type:none}#input-box li{color:#FFF;background-color:#404040;padding:5px;width:300px;margin:0px;float:left;clear:both;margin-bottom:10px;-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript-learning</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<div class="input-container">
<input type="text" id="input-display">
<button onclick = "clickme()">Add input text</button>
<button onclick= "clearInput()">clear Input Box</button>
<button onclick= "delLast()">Del Last</button>
</div> <!--input-container -->
<div id ="main-content-container">
<ul id= "input-box">
</ul>
</div> <!--input-box -->
<div class="array-div">
</div>
</div> <!-- container -->
<!-- javascripts -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/underscore/underscore.min.js"></script>
<script src="bower_components/backbone/backbone-min"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
You need to add the click handler after creating the close button
var inputBox = document.getElementById('input-box');
var inputDisplay = document.getElementById('input-display');
function clickme() {
if (inputDisplay.value == "") {
alert("please put something in the input field.");
} else {
//create a new li
var li = document.createElement('li');
//add the input text to it as text
li.appendChild(document.createTextNode(inputDisplay.value));
//create a new anchor
var a = document.createElement('a');
a.href = "#";
//since id of an element must be unique, use classname
a.className = 'closebtn';
//add the click handler
a.addEventListener('click', closeHandler);
//add the anchor to li
li.appendChild(a);
//add the li to the ul
inputBox.appendChild(li);
}
}
function closeHandler() {
this.parentNode.remove();
}
function clearInput() {
inputBox.innerHTML = "";
}
function delLast() {
if (inputBox.innerHTML === "") {
alert("There is nothing to delete");
} else {
var lastInputText = inputBox.lastChild;
lastInputText.remove();
}
}
.container {
min-height: 400px;
width: 100%;
background-color: #999;
color: #fff;
float: left
}
.input-container {
padding: 10px;
background-color: #777;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px
}
a.closebtn {
background-color: #8B8B8B;
float: right;
padding: 1px 3px;
margin: 0px;
color: #fff;
text-decoration: none
}
#input-box {
list-style-type: none
}
#input-box li {
color: #FFF;
background-color: #404040;
padding: 5px;
width: 300px;
margin: 0px;
float: left;
clear: both;
margin-bottom: 10px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript-learning</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<div class="input-container">
<input type="text" id="input-display">
<button onclick="clickme()">Add input text</button>
<button onclick="clearInput()">clear Input Box</button>
<button onclick="delLast()">Del Last</button>
</div>
<!--input-container -->
<div id="main-content-container">
<ul id="input-box">
</ul>
</div>
<!--input-box -->
<div class="array-div">
</div>
</div>
<!-- container -->
<!-- javascripts -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/underscore/underscore.min.js"></script>
<script src="bower_components/backbone/backbone-min"></script>
<script src="assets/js/script.js"></script>
</body>
</html>

Need to Toggle DIV Visibility for 2 DIVs

I need show a DIV full of dimensions and weights in English measure, and have a link allowing the user to toggle to a hidden DIV that instead displays Metric. Trying the markup below, but it's not working. It refuses to toggle. I've tested with the first div given no style and with its style'"display: block;" and neither works. What am I missing?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
<!--
body {
color:#000000;
background-color:#FFFFFF;
}
a { color:#0000FF; }
a:visited { color:#800080; }
a:hover { color:#008000; }
a:active { color:#FF0000; }
-->
</style>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript">
function toggle_visibility(eng, met) {
var e1 = document.getElementById(eng);
var e2 = document.getElementById(met);
if(e1.style.display == 'block')
e1.style.display = 'none';
e2.style.display = 'block';
else
e1.style.display = 'block';
e2.style.display = 'none';
}
</script>
</head>
<body>
<div id="eng" style="display: block;">
This is English<br />
Convert to Metric
</div>
<div id="met" style="display: none;">
This is Metric<br />
Convert to English
</div>
</body>
</html>
Try this if-statement:
if(e1.style.display == 'block') {
e1.style.display = 'none';
e2.style.display = 'block';
} else {
e1.style.display = 'block';
e2.style.display = 'none';
}
Got it working. I thought I'd post the solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
<!--
body {
color:#000000;
background-color:#FFFFFF;
}
a { color:#0000FF; }
a:visited { color:#800080; }
a:hover { color:#008000; }
a:active { color:#FF0000; }
-->
</style>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript">
function toggle_visibility() {
var e1 = document.getElementById("eng");
var e2 = document.getElementById("met");
if(e1.style.display == 'block') {
e1.style.display = 'none';
e2.style.display = 'block';
}
else {
e1.style.display = 'block';
e2.style.display = 'none';
}
}
</script>
</head>
<body>
<div id="eng" style="display: block;">
This is English<br />
Convert to Metric
</div>
<div id="met" style="display: none;">
This is Metric<br />
Convert to English
</div>
</body>
</html>

Categories

Resources