Click off menu/div to close - javascript

I've been trying to make my menu close when I click anywhere on the page except for within the menu.
I managed to achieve this for when a link is clicked within the menu by giving it the same onclick function as the menu button, but I am not succeeding at clicking off the menu to close it.
http://codepen.io/anon/pen/LEvdmW
JS
function setVisibility(id) {
var targetButton;
switch( id ) {
case "layer":
targetButton = "button";
break;
}
if (document.getElementById(targetButton).value == 'Close') {
document.getElementById(targetButton).innerHTML = 'Open';
document.getElementById(targetButton).value = 'Open';
document.getElementById(id).style.display = 'none';
} else {
document.getElementById(targetButton).innerHTML = 'Close';
document.getElementById(targetButton).value = 'Close';
document.getElementById(id).style.display = 'inline';
}
}
HTML
<button name="type" id="button" onclick="setVisibility('layer')">Open</button>
<div id="layer"><a onclick="setVisibility('layer')"> Hello</div>
CSS
#layer {
position: absolute;
left: 8px;
top: 50px;
background-color: #989898;
width: 280px;
height: 100px;
padding: 10px;
color: black;
display: none;
}
button { border:none; background:#989898; color:#fff; padding:10px; outline:none; cursor:pointer;
}

It can be achieved via below code.
$(document).mouseup(function (e)
{
var container = $("YOUR CONTAINER SELECTOR");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});
Working Fiddle: http://jsfiddle.net/LCB5W/153/
Updated Fiddle: http://jsfiddle.net/LCB5W/154/

You can have a backdrop behind the div where you have your onclick event to hide the div. Check the modified code below (modified your code for you to understand):
Working example : DEMO HERE
HTML
<button name="type" id="button" onclick="setVisibility('layer')">Open</button>
<div id="backdrop" onclick="setVisibility('layer')"></div>
<div id="layer">Hello</div>
CSS
#layer {
position: absolute;
left: 8px;
top: 50px;
background-color: white;
width: 280px;
height: 100px;
padding: 10px;
color: black;
display: none;
z-index : 999;
}
#backdrop {
position : absolute;
top : 0;
left : 0;
width : 100%;
height : 100%;
background : black;
opacity : 0.5;
z-index : 2;
display : none;
}
button {
border:none;
background:#989898;
color:#fff;
padding:10px;
outline:none;
cursor:pointer;
}
JS
function setVisibility(id) {
var targetButton;
switch( id ) {
case "layer":
targetButton = "button";
break;
}
if (document.getElementById(targetButton).value == 'Close') {
document.getElementById(targetButton).innerHTML = 'Open';
document.getElementById(targetButton).value = 'Open';
document.getElementById(id).style.display = 'none';
document.getElementById("backdrop").style.display = "none";
} else {
document.getElementById("backdrop").style.display = "block";
document.getElementById(targetButton).innerHTML = 'Close';
document.getElementById(targetButton).value = 'Close';
document.getElementById(id).style.display = 'inline';
}
}

Related

Move li items on click between lists does not work properly

I have to lists and am using a jquery function to move items from one list (id="columns")to the other (id="columns1") when I click on the items in the first list (id="columns").
That part of it works fine, but when I add a new item in the first list (id="columns"), the previously moved items show up in the first list (id="columns").
Is there a way to prevent the moved items to show up in the first list? Is there a way to do it with vanilla js or do I need to use jquery?
This is all part of an to do list app I am creating where you could add tasks, remove them, click on the task to consider it a finished task, etc.
// Create a "close" button and append it to each list item
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
function closeEvent() {
var close = document.getElementsByClassName("close");
for (var i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = "none";
renderGraph();
}
}
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function (ev) {
if (ev.target.tagName !== 'LI') return;
ev.target.classList.toggle('checked');
renderGraph();
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
li.className = "column";
li.draggable = "true";
// order according to time
li.setAttribute("data-time", document.getElementById("myInput1").value);
// order according to time
var inputValue = document.getElementById("myInput").value;
var inputValue1 = document.getElementById("myInput1").value;
var tine = document.getElementById("myInput1");
tine.dateTime = "6:00"
// inputValue2.datetime = "6:00";
var tt = document.createTextNode(inputValue1 + " - ");
li.appendChild(tt);
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("You must write a task!");
} else {
document.getElementById("columns").appendChild(li);
// order according to time start
setTimeout(function () {
var sortItems = document.querySelectorAll("[data-time]");
var elemArray = Array.from(sortItems);
elemArray.sort(function (a, b) {
if (a.getAttribute('data-time') < b.getAttribute('data-time')) { return -1 } else { return 1 }
});
//
document.getElementById("columns").innerHTML = "";
elemArray.forEach(appendFunction);
function appendFunction(item, index) {
document.getElementById("columns").innerHTML += item.outerHTML;
}
afterUpdate();
});
// order according to time end
}
document.getElementById("myInput").value = "";
document.getElementById("myInput1").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = "none";
}
}
}
// Add tasks by pressing enter
// Get the input field
var input = document.getElementById("myInput");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function (event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("myBtn").click();
}
});
// //
// //
var btn = document.querySelector('.add');
var remove = document.querySelector('.column');
function dragStart(e) {
this.style.opacity = '0.4';
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.innerHTML);
};
function dragEnter(e) {
this.classList.add('over');
}
function dragLeave(e) {
e.stopPropagation();
this.classList.remove('over');
}
function dragOver(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
return false;
}
function dragDrop(e) {
if (dragSrcEl != this) {
dragSrcEl.innerHTML = this.innerHTML;
this.innerHTML = e.dataTransfer.getData('text/html');
closeEvent();
}
return false;
}
function dragEnd(e) {
var listItems = document.querySelectorAll('.column');
[].forEach.call(listItems, function (item) {
item.classList.remove('over');
});
this.style.opacity = '1';
}
function addEventsDragAndDrop(el) {
el.addEventListener('dragstart', dragStart, false);
el.addEventListener('dragenter', dragEnter, false);
el.addEventListener('dragover', dragOver, false);
el.addEventListener('dragleave', dragLeave, false);
el.addEventListener('drop', dragDrop, false);
el.addEventListener('dragend', dragEnd, false);
}
function addDragAndDrop() {
var listItems = document.querySelectorAll('.column');
listItems.forEach(addEventsDragAndDrop);
}
afterUpdate();
function afterUpdate() {
closeEvent();
addDragAndDrop();
renderGraph();
}
function addNewItem() {
var newItem = document.querySelector('.input').value;
if (newItem != '') {
document.querySelector('.input').value = '';
var li = document.createElement('li');
var attr = document.createAttribute('column');
var ul = document.querySelector('ul');
li.className = 'column';
attr.value = 'true';
li.setAttributeNode(attr);
li.appendChild(document.createTextNode(newItem));
ul.appendChild(li);
addEventsDragAndDrop(li);
}
}
#myInput1 {
width: 180px;
height: 36px;
margin-right: 10px;
/* margin-left: -40px; */
/* padding: 10px; */
/* color: red; */
/* box-sizing: border-box; */
/* background-color: blue; */
/* display: inline-block; */
}
[draggable] {
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
user-select: none;
/* Required to make elements draggable in old WebKit */
-khtml-user-drag: element;
-webkit-user-drag: element;
}
/* Include the padding and border in an element's total width and height */
* {
box-sizing: border-box;
font-family: 'Josefin Sans', sans-serif;
}
p {
font-weight: 300;
}
h1 {
font-weight: 300;
}
#x-text {
color: #f97350;
font-size: 1.5rem;
}
::placeholder{
color: #777d71;
}
#myInput1:before {
content:'Time:';
margin-right:.6em;
color: #777d71;
}
/* Remove margins and padding from the list */
ul {
margin: 0;
padding: 0;
list-style: none;
}
/* Style the list items */
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
background: #f7f6e7;
font-size: 18px;
transition: 0.2s;
color: rgb(94, 91, 91);
/* make the list items unselectable */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Set all odd list items to a different color (zebra-stripes) */
ul li:nth-child(odd) {
background: #dfddc5;
}
/* Darker background-color on hover */
ul li:hover {
background: rgb(207, 205, 205);
}
/* When clicked on, add a background color and strike out text */
ul li.checked {
background: #888;
color: #fff;
text-decoration: line-through;
}
/* Add a "checked" mark when clicked on */
ul li.checked::before {
content: '';
position: absolute;
border-color: #fff;
border-style: solid;
border-width: 0 2px 2px 0;
top: 10px;
left: 16px;
transform: rotate(45deg);
height: 15px;
width: 7px;
}
/* Style the close button */
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
color: #f97350;
/* font-size: 1.5rem; */
}
.close:hover {
background-color: #f97350;
color: white;
}
/* Style the header */
.header {
background-color: #777d71;
padding: 30px 40px;
color: white;
text-align: center;
}
/* Clear floats after the header */
.header:after {
content: "";
display: table;
clear: both;
}
/* Style the input */
input {
margin: 0;
border: none;
border-radius: 0;
width: 75%;
padding: 10px;
float: left;
font-size: 16px;
}
/* Style the "Add" button */
/* .addBtn {
padding: 10px;
width: 25%;
background: #d9d9d9;
color: #555;
float: left;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
border-radius: 0;
} */
/* .addBtn:hover {
background-color: #bbb;
} */
#finished-tasks {
/* box-sizing: border-box; */
padding: 20px;
display: grid;
align-content: center;
justify-content: center;
background-color:#bbd38b ;
color: white;
margin-bottom: -20px;
margin-top: 40px;
}
#finished-tasks-p {
/* box-sizing: border-box; */
padding: 20px;
display: grid;
align-content: center;
justify-content: center;
background-color:#bbd38b ;
color: white;
margin-bottom: 0;
margin-top: 0;
}
/* #myChart{
margin-top: 50px;
width: 50vw;
height: 100px;
padding-left: 200px;
padding-right: 200px;
} */
/* canvas{
width:1000px !important;
height:auto !important;
margin: auto;
} */
#media only screen and (max-width: 855px){
input {
margin: 10px;
}
#myInput {
display: grid;
width:70vw;
/* align-content: center; */
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDIV" class="header">
<h1>My Daily Tasks</h1>
<p>Add a time and task then press enter. When finished task click on task bar</p>
<p>To delete task click on <span id="x-text">x</span> in the corner of task bar</p>
<input type="time" id="myInput1" value="06:00">
<input name="text" type="text" id="myInput" placeholder="My task...">
<span onclick="newElement()" class="addBtn" id="myBtn"></span>
</div>
<ul id="columns">
<!-- <li draggable="true" class="column">test</li>
<li draggable="true" class="column">test1</li> -->
<!-- <li class="column" draggable="true">w</li>
<li class="column" draggable="true">ff</li>
<li class="column" draggable="true">uuu</li> -->
</ul>
<ul id="columns2">
<h1 id="finished-tasks">finished Tasks</h1>
<p id="finished-tasks-p">Finished tasks would show up here once you have clicked on the task</p>
</ul>
<!-- adding a graph -->
<canvas id="myChart" width="400" height="400"></canvas>
<script src="/graph.js"></script>
<script src="/app.js"></script>
<!--
<div id="element"></div>
<script>
document.getElementById('element').innerHTML = 'Hi';
</script>-->
<script>
$("#columns").on('click', 'li', function () {
$(this).appendTo('#columns2');
});
$("#listC").on('click', 'li', function () {
$(this).appendTo('#listB');
});
</script>
Change your setTimeout call to this:
setTimeout(function () {
var sortItems = Array.from(document.querySelectorAll("[data-time]"))
.filter((item) => !item.classList.contains('checked'))
.sort(function (a, b) {
if (a.getAttribute('data-time') < b.getAttribute('data-time')) { return -1 } else { return 1 }
});
document.getElementById("columns").innerHTML = "";
sortItems.forEach(appendFunction);
function appendFunction(item, index) {
document.getElementById("columns").innerHTML += item.outerHTML;
}
afterUpdate();
});
The key passage is here:
.filter((item) => !item.classList.contains('checked'))
Before, you were selecting all of the items, even the ones that were already checked. This filters those out.
Here's a working JSFiddle you can experiment with. I had to add an event listener to the addBtn to get it to work on there, but your original script is fine when running from my local machine.

JavaScript - Onclick navigation arrow function issue

I'm trying to be create a simple app with a navigation function. My issue is that when the user clicks the navigation it pops up but if the user click outside the navigation content, the content disappears and the navigation arrow doesn't work. Given below is my code,
const menuButtons = document.querySelectorAll('.clickfun');
menuButtons.forEach(button => button.addEventListener('click', toggleButton, false));
function toggleButton() {
const id = this.dataset.id;
const panel = document.getElementById(id);
if (panel.style.display === 'block') {
panel.style.display = 'none';
} else {
panel.style.display = 'block';
}
}
var boxArray = ['box1','box2'];
window.addEventListener('mouseup', function(event) {
for(var i=0; i < boxArray.length; i++){
var box = document.getElementById(boxArray[i]);
if(event.target != box && event.target.parentNode != box) {
box.style.display = 'none';
}
}
});
var anchors = Array.from(document.querySelectorAll('a'));
anchors.map(anchor => {
if(anchor.classList.contains('btn-open') || anchor.classList.contains('btn-down')) {
anchor.addEventListener('click', () => {
if(anchor.classList.contains('btn-open')) {
anchor.classList.remove('btn-open');
anchor.classList.add('btn-down');
}
else {
anchor.classList.add('btn-open');
anchor.classList.remove('btn-down');
}
});
}
});
#box1 {
position: absolute;
top: 67px;
left: 140px;
width: 260px;
height: 55px;
padding: 6px;
display: none;
background: #E2E2E2;
}
.btn-open:after, a {
font-family: "FontAwesome";
content: "\f0de";
color: #333;
font-size: 18px;
}
.btn-down:after, a {
font-family: "FontAwesome";
content: "\f0dd";
color: #333;
font-size: 18px;
text-decoration: none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<div id="box1">
<h2>Options Main Page</h2>
</div>
<h2>Page Content....</h2>
<div id="box2">
<h2>Pops Out two</h2>
</div>
<nav>
<a data-id="box1" class="clickfun btn-down " href="javascript:void(0);"> About us </a><br>
I would really appreciate some help with this. Thanks.
What you need is this in window.addEventListener('mouseup', function(event) { you need to prevent displaying none if click is on clickfun.
!event.target.classList.contains('clickfun')
Please check code here
const menuButtons = document.querySelectorAll('.clickfun');
menuButtons.forEach(button => button.addEventListener('click', toggleButton, false));
function toggleButton() {
const id = this.dataset.id;
const panel = document.getElementById(id);
if (panel.style.display === 'block') {
panel.style.display = 'none';
} else {
panel.style.display = 'block';
}
ChangeArrows();
}
var boxArray = ['box1', 'box2'];
window.addEventListener('mouseup', function(event) {
for (var i = 0; i < boxArray.length; i++) {
var anchor = document.querySelectorAll('.clickfun');
var box = document.getElementById(boxArray[i]);
if (event.target != box && !boxArray.some(a=> a===event.target.parentNode.id) && !event.target.classList.contains('clickfun') && anchor[0].classList.contains('btn-open')) {
box.style.display = 'none';
ChangeArrows();
event.preventDefault();
return;
}
}
});
function ChangeArrows() {
var anchor = document.querySelectorAll('.clickfun');
if (anchor[0].classList.contains('btn-open')) {
anchor[0].classList.remove('btn-open');
anchor[0].classList.add('btn-down');
} else {
anchor[0].classList.add('btn-open');
anchor[0].classList.remove('btn-down');
}
}
#box1 {
position: absolute;
top: 67px;
left: 140px;
width: 260px;
height: 55px;
padding: 6px;
display: none;
background: #E2E2E2;
}
.btn-open:after,
a {
font-family: "FontAwesome";
content: "\f0de";
color: #333;
font-size: 18px;
}
.btn-down:after,
a {
font-family: "FontAwesome";
content: "\f0dd";
color: #333;
font-size: 18px;
text-decoration: none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />
<div id="box1">
<h2>Options Main Page</h2>
</div>
<h2>Page Content....</h2>
<div id="box2">
<h2>Pops Out two</h2>
</div>
<nav>
<a data-id="box1" class="clickfun btn-down" href="javascript:void(0);"> About us </a><br>

Prevent inside contents inside parent container from making the parent disappear

I have this script that uses a toggle button to show or hide a targeted parent container. There is two correct ways that the parent class container hides by
pressing the toggle button the second time or by clicking outside the parent class container. So it works perfectly but any time I add any thing inside that
parent class container and I click those inside contents it makes the whole parent class container disappear how can I prevent that?
Here is my code
document.addEventListener('DOMContentLoaded', function(){
document.addEventListener('click',closeContainer);
function closeContainer(obj){
var containerVar = document.querySelector('.container');
if(obj.target.className != 'container') {
if (containerVar.style.display === 'flex') {
containerVar.style.display = 'none';
} else if(obj.target.id == 'toggle') {
containerVar.style.display = 'flex';
}
}
}
});
.container{
background-color: orange;
height: 350px;
width: 350px;
margin-left: auto;
margin-right: auto;
display: none;
justify-content: center;
}
.inner-container{
margin-top: 50px;
background-color: red;
height: 200px;
width: 200px;
display: inline-block;
}
<button id='toggle'>Toggle</button>
<div class='container'>
<div class='inner-container'></div>
</div>
You need to capture click events on your container and stop propagation, then there's no need to check the target in your document's event handler:
document.addEventListener('DOMContentLoaded', function() {
// if click event is inside container, then stop propagation
const container = document.querySelector('.container');
container.addEventListener('click', function(e) {
e.stopPropagation();
});
document.addEventListener('click', closeContainer);
function closeContainer(obj) {
var containerVar = document.querySelector('.container');
if (containerVar.style.display === 'flex') {
containerVar.style.display = 'none';
} else if (obj.target.id == 'toggle') {
containerVar.style.display = 'flex';
}
}
});
.container {
background-color: orange;
height: 350px;
width: 350px;
margin-left: auto;
margin-right: auto;
display: none;
justify-content: center;
}
.inner-container {
margin-top: 50px;
background-color: red;
height: 200px;
width: 200px;
display: inline-block;
}
<button id='toggle'>Toggle</button>
<div class='container'>
<div class='inner-container'></div>
</div>
Another solution would be to only have one event handler on document and check if the target or any of its ancestors have the container class (similar to jquery's closest method):
document.addEventListener('DOMContentLoaded', function() {
document.addEventListener('click', closeContainer);
function closeContainer(obj) {
if (closest(obj.target, '.container')) return;
var containerVar = document.querySelector('.container');
if (containerVar.style.display === 'flex') {
containerVar.style.display = 'none';
} else if (obj.target.id == 'toggle') {
containerVar.style.display = 'flex';
}
}
function closest(el, selector) {
const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
while (el) {
if (matchesSelector.call(el, selector)) {
return el;
} else {
el = el.parentElement;
}
}
return null;
}
});
.container {
background-color: orange;
height: 350px;
width: 350px;
margin-left: auto;
margin-right: auto;
display: none;
justify-content: center;
}
.inner-container {
margin-top: 50px;
background-color: red;
height: 200px;
width: 200px;
display: inline-block;
}
<button id='toggle'>Toggle</button>
<div class='container'>
<div class='inner-container'></div>
</div>

Is it possible to have one onlick run different functions one after the other in javascript?

I have to make one of those DO NOT PRESS THE RED BUTTON games for class and basically I need to display text on top of the red button.
Problem is you don't only press the red button once so I'm having trouble with making it work.
I was thinking of making a click counter and using that as basis for an if-else statement.
For example, if(clicks == 0 ) I want the paragraph IDed ButtonText to be "Press me!" at clicks = 1, I want the text to be "Hi!" at clicks = 2, I want to be "Hello." Can someone help me please?
Here's what I have so far including the css and the hypothetical if else statement:
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("counter").innerHTML = clicks;
};
/*
function Function() {
if(clicks == 0) {
document.getElementById("ButtonText").innerHTML = "Press Me!"
}
if else(clicks == 1) {
document.getElementById("ButtonText").innerHTML = "Hi"
}
else(clicks == 2) {
document.getElementById("ButtonText").innerHTML = "Hello."
}
}
*/
div {
font: Arial;
position: fixed;
margin: 13% 0 0 38%;
font-size: 58px;
color: white;
width: 380px;
height: 480px;
border: 0px black transparent;
cursor: pointer;
}
p {
cursor: pointer;
display: block;
}
#button {
display: block;
width: 665px;
height: 665px;
background: url(Images/Unpressed.jpg) no-repeat top;
cursor: pointer;
margin-left: 30%;
margin-top: 10%;
}
#button:active {
background: url(Images/Pressed.jpg) no-repeat bottom;
}
<p>Clicks: <p id="counter">0</p></p>
<div id="container" onclick="myFunction()">
<p id="ButtonText">Press Me!</p>
</div>
<a id="button" onClick="myFunction()"></a>
You are close. There are some syntax errors in your javascript. if else() is not valid and should be else if(). F12 will show you errors like these in the browser console. Also pay attention to where your brackets and indents are to help with code readability.
Aside from that, just use an event listener to call the function that checks the click value. Something like this would work:
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("counter").innerHTML = clicks;
};
function foo(){
myFunction();
if(clicks == 0){
document.getElementById("ButtonText").innerHTML = "Press Me!";
} else if (clicks == 1) {
document.getElementById("ButtonText").innerHTML = "Hi";
} else if (clicks == 2) {
document.getElementById("ButtonText").innerHTML = "Hello.";
} else {
//more than 3 clicks
}
}
//add an event listener to your button
document.getElementById('ButtonText').addEventListener('click',foo);
Here it is in a JS Fiddle example: https://jsfiddle.net/igor_9000/bbtawaff/
Hope that helps.
var clicks = 0;
var clicks = 0;
function myFunction() {
clicks += 1;
var greetings= ["hi","hello","Press Me!"];
document.getElementById("counter").innerHTML = clicks;
document.getElementById("ButtonText").innerHTML = greetings[clicks % greetings.length];
};
/*function Function(){
if(clicks == 0){
document.getElementById("ButtonText").innerHTML = "Press Me!"}
if else(clicks == 1){
document.getElementById("ButtonText").innerHTML = "Hi"}
else(clicks == 2){
document.getElementById("ButtonText").innerHTML = "Hello."}
} */
div{
font: Arial;
position: fixed;
margin: 13% 0 0 38%;
font-size: 58px;
color: white;
width: 380px;
height: 480px;
border: 0px black transparent;
cursor: pointer;
}
p{
cursor: pointer;
display: block;}
#button {
display: block;
width: 665px;
height: 665px;
background: url(Images/Unpressed.jpg) no-repeat top;
cursor: pointer;
margin-left: 30%;
margin-top: 10%;
}
#button:active {
background: url(Images/Pressed.jpg) no-repeat bottom;
}
<p>Clicks: <p id="counter">0</p></p>
<div id="container" onclick="myFunction()"><p id="ButtonText">Press Me!</p></div>
<a id="button" onClick="myFunction()"></a>
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("counter").innerHTML = clicks;
};
/*function Function(){
if(clicks == 0){
document.getElementById("ButtonText").innerHTML = "Press Me!"}
if else(clicks == 1){
document.getElementById("ButtonText").innerHTML = "Hi"}
else(clicks == 2){
document.getElementById("ButtonText").innerHTML = "Hello."}
} */
div{
font: Arial;
position: fixed;
margin: 13% 0 0 38%;
font-size: 58px;
color: white;
width: 380px;
height: 480px;
border: 0px black transparent;
cursor: pointer;
}
p{
cursor: pointer;
display: block;}
#button {
display: block;
width: 665px;
height: 665px;
background: url(Images/Unpressed.jpg) no-repeat top;
cursor: pointer;
margin-left: 30%;
margin-top: 10%;
}
#button:active {
background: url(Images/Pressed.jpg) no-repeat bottom;
}
<p>Clicks: <p id="counter">0</p></p>
<div id="container" onclick="myFunction()"><p id="ButtonText">Press Me!</p></div>
<a id="button" onClick="myFunction()"></a>
Try the following:
<script>
var clicks = 0;
var myFunction = function() {
if(clicks == 0) return false // not sure if you would want to return false here, it would prevent the increment of clicks
if(clicks%2==0){
document.getElementById("elementToChange").innerHTML = "new value";
} else {
alert('hello');
}
clicks += 1;
document.getElementById("counter").innerHTML = clicks;
};
</script>
<div>Clicks: <p id="counter">0</p></div>
<input type="button" id="container" onClick="myFunction();" value="clickme1"/>
Using the modulo (%) operator will accomplish your task
Play around with it and use the console to see what the JS does each time you click
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators
See This Fiddle https://jsfiddle.net/coolbhes/7yhkfqq9/
var clicks = 0;
function myFunction() {
clicks += 1;
var greetings= ["hi","hello","Press Me!","add As many you like..."];
document.getElementById("counter").innerHTML = clicks;
document.getElementById("ButtonText").innerHTML = greetings[clicks % greetings.length];
};
document.getElementById('ButtonText').addEventListener('click',myFunction);

Close Div On Click Outside

I'm currently designing a website in which a user clicks on a button and an overlay and box fades in with various contents. When the user either clicks a close button or clicks outside the box, the box and all the contents fade out. Here's a little bit of code I've already produced:
HTML
<div id="overlay"></div>
<div id="specialBox">
<p style="text-align: center">Special box content.</p>
<button type="button" onmousedown="toggleOverlay()">Close Overlay</button>
</div>
CSS
div#overlay {
background: #000;
display: none;
height: 100%;
left: 0px;
position: fixed;
text-align: center;
top: 0px;
width: 100%;
z-index: 2;
}
div#specialBox {
background: #fff;
color: #000;
display: none;
position: absolute;
z-index: 3;
margin: 150px auto 0px auto;
width: 500px;
height: 300px;
left: 425px;
}
JavaScript
function toggleOverlay(){
var overlay = document.getElementById('overlay');
var specialBox = document.getElementById('specialBox');
overlay.style.opacity = .8;
if(overlay.style.display == "block"){
overlay.style.display = "none";
specialBox.style.display = "none";
} else {
overlay.style.display = "block";
specialBox.style.display = "block";
}
}
jQuery (may be incorrect syntax)
$('html').click(function() {
if (document.getElementById('#specialBox').***IS_VISIBLE***) {
$("#specialBox").fadeOut(300);
$("#overlay").fadeOut(300);
}
});
An example can be found on http://www.madeon.fr when you click on "Newsleter". You can both click a close button and click outside to close it. Now, my question is how can I achieve that with my work?
I figured out the main problem. I simply deleted my jQuery and added "onmousedown='toggleOverlay()'" as an attribute to div#overlay. Then when I clicked the overlay the box disappeared.
Here's the new HTML:
<div id="overlay" onmousedown="toggleOverlay()"></div>
You can do it this way: using $(document).click
The below jsfiddle is for your help: http://jsfiddle.net/jec7rmw6/2/
function toggleOverlay(){
if($("#specialBox").is(":visible"))
{
$('#specialBox').fadeOut(300);
}
}
jQuery('#specialBox').click(
function (e) {
e.stopPropagation();
}
);
$(document).click(function() {
if($("#specialBox").is(":visible"))
{
$('#specialBox').fadeOut(300);
}
});

Categories

Resources