Hide popup window if click out his area [duplicate] - javascript

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.

Related

How to edit array item using javascript

I am pretty new to js. I am trying to complete a todo sort of app. I have been able to create, render and delete an array item, but I am having trouble editing.
All these operations are done with the uuidv4 library to generate an id for each array item created.
With an individual id selected for an array item, I am generating dynamic buttons, one for deleting the array item, the other one for editing.
Upon clicking edit, I want to open up a modal that contains the content of the selected array item. After making the changes, the edit button inside the modal should call upon an edit function to update the changes and then rerender the array.
My issue is that I can't open up the modal dialog box when clicking the edit button.
This is the code to create the necessary structure, the code for creating, rendering and deleting is not included as they are working properly.
// Generate the DOM structure for a todo
const generateTodoDOM = function(todo) {
const todoEl = document.createElement("div");
const checkbox = document.createElement("input");
const label = document.createElement("label");
checkbox.appendChild(label);
todoEl.setAttribute("id", "myTodos");
const textEl = document.createElement("p");
const editButton = document.createElement("button");
editButton.setAttribute("id", "modal-btn");
const removeButton = document.createElement("button");
const createDate = document.createElement("p");
createDate.textContent = `Created: ${dateCreated}`;
createDate.style.color = "#956E93";
// Setup the todo text
textEl.textContent = todo.text;
todoEl.appendChild(textEl);
// Setup the remove button
removeButton.textContent = "x";
todoEl.appendChild(removeButton);
removeButton.addEventListener("click", function() {
removeTodo(todo.id);
saveTodos(todos);
renderTodos(todos, filters);
});
// TODO: Setup the edit note button
editButton.textContent = "Edit Todo";
todoEl.appendChild(editButton);
editButton.addEventListener("click", function() {
//Launch the modal
editModal(todo.id);
});
// Setup todo checkbox
checkbox.setAttribute("type", "checkbox");
checkbox.checked = todo.completed;
todoEl.appendChild(checkbox);
checkbox.addEventListener("change", function() {
toggleTodo(todo.id);
saveTodos(todos);
renderTodos(todos, filters);
});
todoEl.appendChild(createDate);
return todoEl;
};
The code for the modal is the following:
//Edit modal todo by id
const editModal = function(id) {
const todoIndex = todos.findIndex(function(todo) {
return todo.id === id;
});
if (todoIndex > -1) {
const modal = document.querySelector("#my-modal");
const modalBtn = document.querySelector("#modal-btn");
const editTodoContentBtn = document.querySelector("#submitEditTodo")
const closeBtn = document.querySelector(".close");
// Events
modalBtn.addEventListener("click", openModal);
closeBtn.addEventListener("click", closeModal);
editTodoContentBtn.addEventListener("click", editTodo)
window.addEventListener("click", outsideClick);
// Open
function openModal() {
modal.style.display = "block";
}
// Close
function closeModal() {
modal.style.display = "none";
}
// Close If Outside Click
function outsideClick(e) {
if (e.target == modal) {
modal.style.display = "none";
}
}
//Edit the content of the textarea
function editTodo(e) {
editTodo(id)
}
}
};
When clicking the submitEditTodo button the following edit function should be fired:
//Edit todo by id
const editTodo = function(id) {
const editTodoContent = document.querySelector('#editTodo')
const todoIndex = todos.findIndex(function(todo) {
return todo.id === id;
});
if (todoIndex > -1) {
editTodoContent.value = todos.text
saveTodos(todos)
renderTodos(todos, filters);
}
};
The saveTodos and renderTodos are functioning properly with other functions for creating, rendering and deleting.
This is the HTML code:
<!-- Edit modal -->
<div id="my-modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Edit Todo</h2>
</div>
<div class="modal-body">
<textarea name="" class="editTextArea" id="editTodo" rows="10"></textarea>
<button class="button" id="submitEditTodo">Edit Todo</button>
</div>
<div class="modal-footer">
<!-- <h3>Modal Footer</h3> -->
</div>
</div>
<!-- End modal -->
and this is the CSS for the modal:
/*
Edit todo modal start
*/
:root {
--modal-duration: 1s;
--modal-color: #BB8AB8;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
height: 100%;
width: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
margin: 10% auto;
width: 35%;
box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
animation-name: modalopen;
animation-duration: var(--modal-duration);
}
.editTextArea{
width:100%
}
.modal-header h2,
.modal-footer h3 {
margin: 0;
}
.modal-header {
background: var(--modal-color);
padding: 15px;
color: #fff;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.modal-body {
padding: 10px 20px;
background: #fff;
}
.modal-footer {
background: var(--modal-color);
padding: 10px;
color: #fff;
text-align: center;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
}
.close {
color: #ccc;
float: right;
font-size: 30px;
color: #fff;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#keyframes modalopen {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/*
Edit todo modal end
*/
Thanks
Below are a few pointers to where you might need adjustments to achieve what you want.
Currently you are adding new listeners to the modal every time you click an edit button for a todo. This should probably only be set once. Alternatively you should remove the listeners when the modal is closed.
Your function editModal does not actually open the modal. What it does is add a listener to the #modal-btn button which will then open the modal the next time you click the button.
You are setting id's for both the outer div and the edit button, but the id's are not based on anything related to the todo element you are creating. So effectively all those elements end up with the same id. An id (short for identifier) is usually meant to be unique. For grouping of multiple elements you should instead use the class attribute.
Your function "editTodo" calls itself. Recursing indefinitely. Beware of reusing function names.
With that said the below code is a crude way to do what I think you want to do based on the snippets you provided:
// Open
const openModal = function() {
document.querySelector("#my-modal").style.display = "block";
}
// Close
const closeModal = function() {
document.querySelector("#my-modal").style.display = "none";
}
function initModal() {
const modal = document.querySelector("#my-modal");
const closeBtn = document.querySelector(".close");
// Events
closeBtn.addEventListener("click", closeModal);
window.addEventListener("click", outsideClick);
// Close If Outside Click
function outsideClick(e) {
if (e.target == modal) {
modal.style.display = "none";
}
}
}
const filters = []; // dummy variable
// Generate the DOM structure for a todo
var todos = []
function generateTodoDOM(todo) {
todos.push(todo);
const todoEl = document.createElement("div");
const checkbox = document.createElement("input");
const label = document.createElement("label");
checkbox.appendChild(label);
todoEl.setAttribute("id", "my-todos-" + todo.id);
const textEl = document.createElement("p");
const editButton = document.createElement("button");
editButton.setAttribute("id", "modal-btn-" + todo.id);
const removeButton = document.createElement("button");
const createDate = document.createElement("p");
createDate.textContent = 'Created: ' + new Date();
createDate.style.color = "#956E93";
// Setup the todo text
textEl.textContent = todo.text;
todoEl.appendChild(textEl);
// Setup the remove button
removeButton.textContent = "x";
todoEl.appendChild(removeButton);
removeButton.addEventListener("click", function() {
removeTodo(todo.id);
saveTodos(todos);
renderTodos(todos, filters);
});
// TODO: Setup the edit note button
editButton.textContent = "Edit Todo";
todoEl.appendChild(editButton);
editButton.addEventListener("click", function() {
//Launch the modal
editModal(todo.id);
openModal();
});
// Setup todo checkbox
checkbox.setAttribute("type", "checkbox");
checkbox.checked = todo.completed;
todoEl.appendChild(checkbox);
checkbox.addEventListener("change", function() {
toggleTodo(todo.id);
saveTodos(todos);
renderTodos(todos, filters);
});
todoEl.appendChild(createDate);
return todoEl;
};
var editFn
//Edit modal todo by id
const editModal = function(id) {
const todoIndex = todos.findIndex(function(todo) {
return todo.id === id;
});
if (todoIndex > -1) {
const modal = document.querySelector("#my-modal");
const editElm = document.querySelector("#editTodo");
const editTodoContentBtn = document.querySelector("#submitEditTodo")
editElm.value = todos[todoIndex].text;
// Events
editTodoContentBtn.removeEventListener("click", editFn)
//Edit the content of the textarea
editFn = function(e) {
editTodo(id)
closeModal()
}
editTodoContentBtn.addEventListener("click", editFn)
}
};
//Edit todo by id
const editTodo = function(id) {
const editTodoContent = document.querySelector('#editTodo')
const todoIndex = todos.findIndex(function(todo) {
return todo.id === id;
});
if (todoIndex > -1) {
todos[todoIndex].text = editTodoContent.value;
saveTodos(todos)
renderTodos(todos, filters);
}
};
const saveTodos = function(todos) {
// dummy method, we're keeping it in memory for this example
}
const renderTodos = function(todosToRender) {
todos = []; // clear current in-memory array
var todoList = document.getElementById("todo-container");
while (todoList.firstChild) {
todoList.removeChild(todoList.firstChild);
}
for(var i = 0; i < todosToRender.length; i++) {
todoList.appendChild(generateTodoDOM(todosToRender[i]));
}
};
initModal();
const container = document.getElementById("todo-container");
var generatedTodos = [];
for(var i = 0; i < 10; i++) {
var todo = { text: "Todo " + (i+1), id: "todo-" + i, completed: false};
generatedTodos.push(todo);
}
renderTodos(generatedTodos);
/*
Edit todo modal start
*/
:root {
--modal-duration: 1s;
--modal-color: #BB8AB8;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
height: 100%;
width: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
margin: 10% auto;
width: 35%;
box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
animation-name: modalopen;
animation-duration: var(--modal-duration);
}
.editTextArea{
width:100%
}
.modal-header h2,
.modal-footer h3 {
margin: 0;
}
.modal-header {
background: var(--modal-color);
padding: 15px;
color: #fff;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.modal-body {
padding: 10px 20px;
background: #fff;
}
.modal-footer {
background: var(--modal-color);
padding: 10px;
color: #fff;
text-align: center;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
}
.close {
color: #ccc;
float: right;
font-size: 30px;
color: #fff;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#keyframes modalopen {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/*
Edit todo modal end
*/
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="todo-container">
</div>
<!-- Edit modal -->
<div id="my-modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Edit Todo</h2>
</div>
<div class="modal-body">
<textarea name="" class="editTextArea" id="editTodo" rows="10"></textarea>
<button class="button" id="submitEditTodo">Edit Todo</button>
</div>
<div class="modal-footer">
<!-- <h3>Modal Footer</h3> -->
</div>
</div>
</div>
<!-- End modal -->
</body>
</html>

Dynamic way to hide divs vanilla javascript

Is there a more dynamic way to hide/show divs that are identical in structure with no identifiers?
Click to show
I'm some stuff
<div class="setup" onclick="show(1)">
Click to show
<p class="hidden">
I'm more stuff
</p>
</div>
function show(elem) {
var p = document.getElementsByClassName("hidden");
if (p[elem] != undefined) {
if (p[elem].style.display == "none") {
p[elem].style.display = "block";
} else {
p[elem].style.display = "none";
}
}
}
http://jsfiddle.net/ba7yfmz6/29/
Use this:
<div class="setup" onclick="show(this)">
JavaScript:
function show(elem) {
var paragraph = elem.querySelector(".hidden");
if (paragraph.style.display == "none") {
paragraph.style.display = "block";
} else {
paragraph.style.display = "none";
}
Hopefully this helps!
Yes, there is a way!
You can get all your elements, iterate them via forEach and assign your function to their onclick property:
document.querySelectorAll('.setup').forEach(div => {
div.onclick = showElem;
});
Doing this, you can get rid of the onlick on your HTML elements.
To get their child element (the one you want to hide / show, obviously), your show() function can look like this:
function show() {
const hidden = this.getElementsByClassName('hidden')[0];
if (hidden.style.display == 'none') {
hidden.style.display = 'block';
} else {
hidden.style.display = 'none';
}
}
And all together:
document.querySelectorAll('.setup').forEach(div => {
div.onclick = show;
});
function show() {
const hidden = this.getElementsByClassName('hidden')[0];
if (hidden.style.display == 'none') {
hidden.style.display = 'block';
} else {
hidden.style.display = 'none';
}
}
.setup {
border-top: solid #ccc 3px;
border-bottom: solid #ccc 3px;
margin-bottom: 5%;
}
.setup:hover {
cursor: pointer;
}
.hidden {
text-align: center;
font-weight: bold;
border-top: solid black 3px;
border-bottom: solid black 3px;
background-color: yellow;
display: none;
}
<div class="setup">
Click to show
<p class="hidden">
I'm some stuff
</p>
</div>
<div class="setup">
Click to show
<p class="hidden">
I'm more stuff
</p>
</div>
JS Fiddle: http://jsfiddle.net/ba7yfmz6/38/
More info:
forEach
querySelectorAll()
You can use this.
Also, since the div doesn't have a style attribute, checking for style.display === 'none' would always be false on the first click; it would set the the style.display to none. Checking for the computed style would show the hidden element on first click.
function show(el) {
const toggle = el.querySelector('.hidden');
toggle.style.display = window.getComputedStyle(toggle).display === 'none' ? 'block' : 'none';
}
.setup {
border-top: solid #ccc 3px;
border-bottom: solid #ccc 3px;
margin-bottom: 5%;
}
.setup:hover {
cursor: pointer;
}
.hidden {
text-align: center;
font-weight: bold;
border-top: solid black 3px;
border-bottom: solid black 3px;
background-color: yellow;
display: none;
}
<div class="setup" onclick="show(this)">
Click to show
<p class="hidden">
I'm some stuff
</p>
</div>
<div class="setup" onclick="show(this)">
Click to show
<p class="hidden">
I'm more stuff
</p>
</div>
<div class="setup" onclick="show(this)">
Then the JavaScript:
function show(that) {
var hiddenElements = that.getElementsByClassName('hidden');
for (var i = 0; i < hiddenElements.length; i++) {
var style = hiddenElements[i].style;
style.display = style.display == "block" ? "none" : "block";
}
}

Element on a menu not responding to a trigger event

I've made a menu that reveals a drop down menu when you click or touch it. At least that's what happens when you select the word 'Menu2' but unfortunately it's not what happens when you select the words 'Menu3'.
On Menu3, for some reason my code is not recognising the selection of the anchor element and then as a consequence the id of that anchor element is not being passed to the functions which will make the sub-menu appear and disappear.
The strangest thing is that when I replace the 'else if' statement with an 'if' statement the menu under 'Menu2' will appear when I select 'Menu3'!
The thing I took from this was that the querySelectorAll method and the For loop are working. It remains a mystery me why the third menu choice can't be selected.
My question is can anyone work why the menu below 'Menu3' is not opening and closing?
The listeners in the javascript code are activated when the window is loaded.
var timeout = 500;
var closetimer = 0;
var ddmenuitem = 0;
function listen(elem, evnt, func) {
if (elem.addEventListener) { //W3C DOMS.
elem.addEventListener(evnt, func, false);
} else if (elem.attachEvent) { //IE DOM 7
var r = elem.attachEvent("on" + evnt, func);
return r;
}
}
function attachListeners() {
var selectors = document.querySelectorAll("a#a2, a#a3");
for (var i = 0; i < selectors.length; i++) {
selectors[i].addEventListener("focus", function(event) {
var id_of_clicked_element = event.target.id
});
if (id_of_clicked_element = 'a2') {
var touch_div = document.getElementById(id_of_clicked_element);
// return false;
} else if (id_of_clicked_element = 'a3') {
touch_div = document.getElementById(id_of_clicked_element);
//return false;
}
}
listen(touch_div, 'touchstart', function(event) {
// get new layer and show it
event.preventDefault();
mopen(id_of_clicked_element);
}, false);
listen(touch_div, 'mouseover', function(event) {
// get new layer and show it
mopen(id_of_clicked_element);
}, false);
listen(touch_div, 'click', function(event) {
// get new layer and show it
mopen(id_of_clicked_element);
}, false);
}
function m1View() {
var y = document.getElementById('m1');
if (y.style.visibility === 'hidden') {
y.style.visibility = 'visible';
} else {
y.style.visibility = 'hidden';
}
}
function m2View() {
var z = document.getElementById('m2');
if (z.style.visibility === 'hidden') {
z.style.visibility = 'visible';
} else {
z.style.visibility = 'hidden';
}
}
// open hidden layer
function mopen(x) { // get new layer and show it
var openmenu = x;
if (openmenu = 'a2') {
m1View();
} else if (openmenu = 'a3') {
m2View();
}
}
window.onload = attachListeners;
#ddm {
margin: 0;
padding: 0;
z-index: 30
}
#ddm li {
margin: 0;
padding: 0;
list-style: none;
float: left;
font: bold 14px arial
}
#ddm li a {
display: block;
margin: 0 0 0 0;
padding: 12px 17px;
width: 130px;
background: #CC0066;
color: #FFF;
text-align: center;
text-decoration: none
}
#ddm li a:hover {
background: #CC0066
}
#ddm div {
position: absolute;
visibility: hidden;
margin: 0;
padding: 0;
background: #EAEBD8;
border: 1px solid #5970B2
}
#ddm div a {
position: relative;
display: block;
margin: 0;
padding: 5px 10px;
width: 130px;
white-space: nowrap;
text-align: left;
text-decoration: none;
background: #EAEBD8;
color: #5C124A;
font: 13px arial;
border: 1px solid #CC0066
}
#ddm div a:hover {
background: #CC0066;
color: #FFF
}
<ul id="ddm">
<li>Menu1</li>
<li>
Menu2
<div id="m1">
Dropdown 1.1
Dropdown 1.2
Dropdown 1.3
Dropdown 1.4
Dropdown 1.5
Dropdown 1.6
</div>
</li>
<li>
Menu3
<div id="m2">
Menu4
</div>
</li>
<li>Menu5</li>
<li>Menu6</li>
</ul>
<div style="clear:both"></div>
A JSfiddle can be found here: https://jsfiddle.net/Webfeet/z9x6Ly6k/27/
Thank you for any help anyone can provide.
NewWeb
I'd suggest a couple of things. First, like Leo Li suggested, I think you may have overcomplicated this a little. For instance, you could replace your attachListeners function with something like this:
function attachListeners() {
var selectors = document.querySelectorAll("a#a2, a#a3");
for (var i = 0; i < selectors.length; i++) {
selectors[i].addEventListener('touchstart', function(event){
event.preventDefault();
mopen(event.target.id);
}, false);
selectors[i].addEventListener('mouseover', function(event){
event.preventDefault();
mopen(event.target.id);
}, false);
selectors[i].addEventListener('click', function(event){
event.preventDefault();
mopen(event.target.id);
}, false);
}
}
But, besides that, one of the biggest problems is in the mopen() function. Instead of checking the value being passed in for x, you're reassigning it. Just switch the equals signs with triple equals, like this:
if (openmenu === 'a2') {
m1View();
} else if (openmenu === 'a3') {
m2View();
}
It's still probably not quite what you're looking for but here's a fork of your JSfiddle with my changes - https://jsfiddle.net/n90ryvfd/
Hope that helps!

Javascript Methods

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

Making a javascript popup draggable

I am creating a JavaScript popup. The code is as below.
The HTML:
<div id="ac-wrapper" style='display:none' onClick="hideNow(event)">
<div id="popup">
<center>
<h2>Popup Content Here</h2>
<input type="submit" name="submit" value="Submit" onClick="PopUp('hide')" />
</center>
</div>
</div>
The CSS:
#ac-wrapper {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: url("images/pop-bg.png") repeat top left transparent;
z-index: 1001;
}
#popup {
background: none repeat scroll 0 0 #FFFFFF;
border-radius: 18px;
-moz-border-radius: 18px;
-webkit-border-radius: 18px;
height: 361px;
margin: 5% auto;
position: relative;
width: 597px;
}
The Script:
function PopUp(hideOrshow) {
if (hideOrshow == 'hide') document.getElementById('ac-wrapper').style.display = "none";
else document.getElementById('ac-wrapper').removeAttribute('style');
}
window.onload = function () {
setTimeout(function () {
PopUp('show');
}, 0);
}
function hideNow(e) {
if (e.target.id == 'ac-wrapper') document.getElementById('ac-wrapper').style.display = 'none';
}
The jsFiddle Link:
http://jsfiddle.net/K9qL4/2/
The Issue:
The above script works fine, but I need to make the popUp draggable.
Here's some code that will do what you want. It relies only on an object called drag to store all its values, but you can easily alter that. The example relies on there being a div with the id of mydiv (a document.write() is used in this instance to supply that) that has a position attribute of absolute or fixed. You can see it in action at Jamie
document.write("<" + "div id='mydiv' style='background:blue; width:100px;"
"height:100px; position:fixed;'>" + "<" + "/div>");
var drag = new Object();
drag.obj = document.getElementById('mydiv');
drag.obj.addEventListener('mousedown', function(e)
{
drag.top = parseInt(drag.obj.offsetTop);
drag.left = parseInt(drag.obj.offsetLeft);
drag.oldx = drag.x;
drag.oldy = drag.y;
drag.drag = true;
});
window.addEventListener('mouseup', function()
{
drag.drag = false;
});
window.addEventListener('mousemove', function(e)
{
drag.x = e.clientX;
drag.y = e.clientY;
var diffw = drag.x - drag.oldx;
var diffh = drag.y - drag.oldy;
if (drag.drag)
{
drag.obj.style.left = drag.left + diffw + 'px';
drag.obj.style.top = drag.top + diffh + 'px';
e.preventDefault();
}
});
Use the
.draggable();
jquery function, here is your updated fiddle:
http://jsfiddle.net/N9rQK/
If you don't want to use jQuery, you should read this subject: Draggable div without jQuery UI

Categories