javascript menu, How to close when mouse outside of div? - javascript

this is my first pure JavaScript script as you can probably tell, by the length of it! I'm at a loss to workout how i can get the child links which are in a div with a class called 'menu' to close when i leave that div.
I've tried to write an If argument to set it to close when i leave the 'A' and also a 'DIV' and that doesn't seem to work?
Any help would be much appreciated and sorry for the overly long code!
Please no Jquery for now, thanks!
<script>
// Variables
var getFirstMenu = document.getElementsByTagName('div');
// Use selectors
var getMenuClasses = document.getElementsByClassName('menu');
// Hide drop down menus
for(var i=0; i < getFirstMenu.length; i++){
getFirstMenu[i].style.visibility = 'hidden';
}
// =============================
// Show Menu on mouseover
function showDropdown(e){
var el = e.target;
if(el.nodeName == 'A'){
for(var i = 0; i < getMenuClasses.length; i++) {
if(el == getMenuClasses[0]){
getFirstMenu[0].style.visibility = 'visible';
}else if(el == getMenuClasses[1]) {
getFirstMenu[1].style.visibility = 'visible';
}else if(el == getMenuClasses[2]){
getFirstMenu[2].style.visibility = 'visible';
}
}
}
}
var getMainMenu = document.getElementById('menu');
getMainMenu.addEventListener('mouseover', function(e){
showDropdown(e);
},false);
// =============================
// Hide Menu on mouseout
function mouseOutMenu(e){
var el = e.target;
if(el.nodeName == 'DIV')
for(var i = 0; i < getFirstMenu.length; i++){
getFirstMenu[i].style.visibility = 'hidden';
}
}
getMainMenu.addEventListener('mouseout', function(e){
mouseOutMenu(e);
}, false);

Add a Handler to the document-object
document.addEventHandler('mouseover', function(){
// close it
}, false);
Or when this is about to hide a submenu: Add the handler to the menu which then hides the menu on mouseover

Look Demo
Code :
// Variables
var getFirstMenu = document.getElementsByTagName('div');
// Use selectors
var getMenuClasses = document.getElementsByClassName('menu');
// Hide drop down menus
for(var i=0; i < getFirstMenu.length; i++){
getFirstMenu[i].style.visibility = 'hidden';
}
// =============================
// Show Menu on mouseover
function showDropdown(e){
var el = e.target;
if(el.nodeName == 'A'){
for(var i = 0; i < getMenuClasses.length; i++) {
if(el == getMenuClasses[0]){
getFirstMenu[0].style.visibility = 'visible';
}else if(el == getMenuClasses[1]) {
getFirstMenu[1].style.visibility = 'visible';
}else if(el == getMenuClasses[2]){
getFirstMenu[2].style.visibility = 'visible';
}
}
}
}
var getMainMenu = document.getElementById('menu');
getMainMenu.addEventListener('mouseover', function(e){
showDropdown(e);
},false);
// =============================
// Hide Menu on mouseout
function mouseOutMenu(e){
var el = e.target;
//if(el.nodeName == 'A')
for(var i = 0; i < getFirstMenu.length; i++){
getFirstMenu[i].style.visibility = 'hidden';
}
}
for(var i = 0; i < document.getElementsByTagName('div').length; i++){
document.getElementsByTagName('div')[i].addEventListener('mouseout', function(e){
mouseOutMenu(e);
}, false);
}

Related

How to change the background of multiple buttons when reading from Session Storage

I'm trying to get all the buttons on this page begin neutral and then turn red when the page loads and finally turn green whenever a checklist on the next page is completed. I can only seem to get the first button to work but the others aren't doing anything. Any advice? All other attempts are in the comments.
function initial(){
if (localStorage.getItem("run") == null) {
/* var form = document.getElementById("myForm");
var idObject = {};
idObject[form.elements[0].id].("false");
for(var i = 1; i < form.length ; i++){
idObject[form.elements[i].id].push("false");
}
sessionStorage.setItem("savedIds",JSON.stringify(idObject)); */
/* var ids = [ {area:"kitchen",done:"true"},
{area:"livingroom",done:"false"},
{area:"bathroom",done:"false"},
{area:"dining",done:"false"},
{area:"bredroom",done:"false"}]; */
/* var ids = {"kitchen":false,
"livingroom":true,
"bathroom":false,
"dining":false,
"bedroom":false}; */
var ids = [false,false,false,false,false];
sessionStorage.setItem("savedIds",JSON.stringify(ids));
localStorage.setItem("run", true);
}
}
function loader(){
var form = document.getElementById("myForm");
var obj = JSON.parse(sessionStorage.getItem("savedIds"));
for(var i = 0;i < 5;i++){
if(obj[i] == true){
document.getElementById(form.elements[i].id).style.backgroundColor = "green";
return false;
}else{
document.getElementById(form.elements[i].id).style.backgroundColor = "red";
return false;
}
}
}
So I have mentioned this on the forum but I haven't been able to quite solve this. It is killing me since I have spent days on this alone. Any advice would be great!
Something to note, this is the function on the checklist page that reads the checklist and turns the buttons to green. There is also an issue where the color doesn't change the green because of a "VM915:1 Uncaught SyntaxError: Unexpected token , in JSON at position 4"
function checkTasks(form){
var count = 0;
for(var i = 0;i<form.task.length;i++){
if(form.task[i].checked){
count++;
}
}
if(count == form.task.length){
var obj = JSON.parse(sessionStorage.getItem("savedIds"));
obj[0] = true;
sessionStorage.setItem("savedIds",obj);
//sessionStorage.setItem("kitchen","true");
window.open("http://localhost:8080/Project/home.html","_self");
}else{
alert("You have not completed all the tasks! Please check all the boxes to indicate you have completed the tasks. If there is an issue, write it in the other box.");
}
}
function initial(){
if (localStorage.getItem("unitrun") === null) {
var form = document.getElementById("myForm");
var tot = form.length;
for(var i = 0; i < tot ; i++){
sessionStorage.setItem(form.elements[i].id,"false");
}
localStorage.setItem("unitrun", true);
}
}
function loader(){
var form = document.getElementById("myForm");
var tot = form.length;
for(var i = 0; i < tot ; i++){
if(sessionStorage.getItem(form.elements[i].id) === "true"){
document.getElementById(form.elements[i].id).disabled = true;
}else{
document.getElementById(form.elements[i].id).disabled = false;
}
}
}
function checkTasks(form){
var count = 0;
var list = document.getElementById("tasks").getElementsByTagName("li");
var tot = list.length;
for(var i = 0;i < tot;i++){
if(form.task[i].checked){
count++;
}
}
if(count == tot){
sessionStorage.setItem("kitchen","true");
window.open("http://localhost:8080/Project/home.html","_self");
}else{
alert("You have not completed all the tasks! Please check all the boxes to indicate you have completed the tasks. If there is an issue, write it in the other box.");
}
}
The best way to do this (IMO) is maximizing the power of CSS
for example:
CSS
button.myBtn {
color: initial;
}
body.loaded button.myBtn {
color: red;
}
body.processed button.myBtn {
color: green;
}
Add class myBtn to all of the buttons whose color you want to change. Then in your javascript all you need to do is add class loaded and class processed to document.body to get all of your buttons' colors to change.

How to delete td without any id

Hello i want to remove "Have you served in the military ?" and "No" if Answer is "No" but when it will "Yes" than it should show.
Whatever i have tried but it's not working
<script type="text/javascript">
(function(){
for(i = 0; (a = document.getElementsByTagName("td")[i]); i++){
if(document.getElementsByTagName("span")[i].innerHTML.indexOf('Have you served in the military') > -1){
document.getElementsByTagName("td")[i].style.display = "none";
}
}
})();
</script>
You could use child of the element or just do a find replace or even hide and show.
You can get all td elements like you already did and than get the span elements inside them:
var tds = document.getElementsByTagName('TD');
for (var i = 0, l = tds.length; i != l; ++i) {
var spans = tds[i].getElementsByTagName('SPAN');
for (var j = 0, l2 = spans.length; j != l2; ++j) {
var span = spans[j];
if ((span.textContent = span.innerText).indexOf('Have you served in the military') != -1) {
span.style.display = 'none';
break;
}
}
}
EDIT: OP wants to only delete the span if there is a td with the content "No" (also delete the td element)
var tds = document.getElementsByTagName('TD');
var tdsLength = tds.length;
var answerNoFound = false;
for (var i = 0; i != tdsLength; ++i) {
var td = tds[i];
if ((td.textContent = td.innerText) == 'No') {
td.style.display = 'none';
answerNoFound = true;
break;
}
}
if (answerNoFound)
for (var i = 0; i != tdsLength; ++i) {
var spanFound = false;
var spans = tds[i].getElementsByTagName('SPAN');
for (var j = 0, l = spans.length; j != l; ++j) {
var span = spans[j];
if ((span.textContent = span.innerText).indexOf('Have you served in the military') != -1) {
span.style.display = 'none';
spanFound = true;
break;
}
}
if (spanFound)
break;
}
It looks like you have an application form and document probably has more spans, some outside the td elements, so you don't get correct selection of spans versus td.
So when you are comparing span content, it is most likely not the span that is inside your looped td.
<script type="text/javascript">
(function(){
for(i = 0; (a = document.getElementsByTagName("td")[i]); i++){
if(a.getElementsByTagName("span")[0].innerHTML.indexOf('Have you served in the military') > -1){
a.style.display = "none";
}
}
})();
</script>
I changed the if statement to select span inside your looped td, that should do it.

Add class active when clicking menu link with JAVASCRIPT

HTML
<div id="top" class="shadow">
<ul class="gprc">
<li>Home</li>
<li>Text1</li>
<li>Text2</li>
<li>Text3</li>
<li>Text4</li>
</ul>
Javascript
window.onload = setActive;
function setActive() {
aObj = document.getElementById('top').getElementsByTagName('a');
var found = false;
for (i = 0; i < aObj.length; i++) {
if (document.location.href.indexOf(aObj[i].href) >= 0) {
aObj[i].className = 'active';
found = true;
}
}
if (!found) {
aObj[0].className = 'active';
}
}
The problem is that the menu home link remains selected or active all the time even if i click on other links and I would like to make it not selected on loading of the page and also to remain non-selected while other link that i clicked and i am on the specific landing page remains selected. Please only Javascript no JQUERY.
Try this:
window.onload = setActive;
function setActive() {
var aObj = document.getElementById('top').getElementsByTagName('a');
var found = false;
for(var i=aObj.length-1; i>=1 && !found; i--) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
found = true;
}
}
//if you never want home selected remove the next
if(!found && document.location.href.replace(/\/$/, "") == aObj[0].href.replace(/\/$/, ""))
aObj[0].className = 'active';
}
With this way you start at the end of the list, and when you find a coincidence it stop the search of an active link.
I hope it helps you
function setActive() {
var top = document.getElementById('top'),
aObj = top.getElementsByTagName('a'),
href = document.location.href,
found = false;
for (var i = 0; i < aObj.length || !found; i++) {
if (href.indexOf(aObj[i].href) >= 0) {
aObj[i].className = 'active';
found = true;
}
}
if (!found) {
aObj[0].className = 'active';
}
//Listen for link clicks
function listener(e) {
if(e.target.tagName === "A") {
for (var i = 0; i<aObj.length; i++) {//remove previous class
aObj[i].className = "";
}
e.target.className = "active";
}
}
if(top.addEventListener) {
top.addEventListener(listener);
} else if(top.attachEvent) {
top.attachEvent(listener);
}
}
You're going to need to listen to the click event so you can determine if one of your links is pressed. I'm going to do this using some simple delegation

new content replacing the old one hide and show

I amd working with hiding and showing divs, which have different contents. When i click on a link, i want a div to be shown. But when i click on another link, i want the new content to replace the previous one. Right now, it falls under it instead of replacing it. Any solution?
Javascript
function show(){
var links = {
link1: "content1",
link2: "content2",
link3: "content3",
link4: "content4"
};
var id = event.target.id;
var a = document.getElementsByTagName("a");
document.getElementById(links[id]).style.visibility = 'visible';
}
function init(){
var divs = document.getElementsByTagName("div");
for (i = 0; i < divs.length; i++) {
if (divs[i].className == "div") {
divs[i].style.visibility = 'hidden';
}
}
var a = document.getElementsByTagName("a");
for(i = 0; i < a.length; i++){
a[i].onclick = show;
}
}
window.onload = init;
You need to run the block of code that hides them all before showing the one you want, every time.
Make this:
function hideAll() {
var divs = document.getElementsByTagName("div");
for (i = 0; i < divs.length; i++) {
if (divs[i].className == "div") {
divs[i].style.visibility = 'hidden';
}
}
Remove this code from init() and replace it with a call to hideAll() and add a call to hideAll() at the beginning of show().

How to stop event when user clicks inside certain divs using JavaScript

I want this code to check if the user has clicked inside the open box and if so then it will keep it open, also if the user clicks outside the box it will close.
http://jsfiddle.net/MTJa5/26/
var boxes = function(){
var divClicks = document.getElementsByClassName("clickToShow");
for(i=0; i < divClicks.length; i++){
var click = divClicks[i];
var clickEvent = function(){
click.addEventListener("click", function(e){
var currentClass= this.getElementsByTagName('div')[0].className;
var divs = document.getElementsByClassName('openedBox');
for(var i = 0; i < divs.length; i++){
divs[i].setAttribute("class", "closedBox");
}
if(currentClass === "openedBox"){
this.childNodes[3].setAttribute("class", "closedBox");
} else {
this.childNodes[3].setAttribute("class", "openedBox");
}
},false);
}();
}
}();
Instead of binding several event listeners, you can also bind just one click event, and use the event.target property to check where you've clicked.
The updated code is less comples, and easier to maintain.
Demo: http://jsfiddle.net/MTJa5/28/
var hellos = function() {
function closeAllButThisBox(targ) {
var allBoxes = document.getElementsByClassName('openedBox');
for (var i=allBoxes.length-1; i>=0; i--) {
if (allBoxes[i] !== targ) {
allBoxes[i].className = 'closedBox';
}
}
}
window.addEventListener('click', function(ev) {
var targ = ev.target;
// Traverse the tree, until you hit the desired / root element
while (targ && targ !== document.documentElement) {
if (targ.className.indexOf('openedBox') !== -1) {
closeAllButThisBox(targ);
// Do nothing when clicking inside an opened box
return;
}
// This will open boxes, if closed, when clicking at the <p>
if (targ.tagName.toLowerCase() === 'p' && targ.parentNode.className.indexOf('clickToShow') !== -1) {
closeAllButThisBox(targ.parentNode);
targ.parentNode.getElementsByTagName('div')[0].className = 'openedBox';
return;
}
targ = targ.parentNode;
}
// At this point, the click is not at the right place.
// Close all boxes by removing the closedBox class names
var boxes = document.getElementsByClassName('openedBox');
for (var i=boxes.length-1; i>=0; i--) {
boxes[i].className = 'closedBox';
}
}, false);
}();

Categories

Resources