JavaScript: How can I change the visibility of an element when clicked? - javascript

I'm trying to make a code that allows me to make click on any part of the screen and when I click the screen should display the message "click!"
By far I got the next code
html:
<html>
<head>
<title>Sense events anywhere</title>
<script type="text/javascript" src="anywhere.js"></script>
<link type="text/css" rel="stylesheet" href="anywhere.css" />
</head>
<body id="body" onload="init();">
<div id="message"> Click! </div>
</body></html>
JavaScript:
var e;
function init(){
e = document.getElementById("message");
document.getElementById("message").style.visibility = "hidden";
e.onmousedown = displayIt(e);
e.onmouseup = hideIt;
}
function displayIt(e) {
e.style.visibility = "visible";
}
function hideIt() {
e.style.visibility = "hidden";
}
CSS:
body {
}
div#message{
}
By far I only tried to turn the message visible and "invisible" when clicked but it doesn't work
Sorry for my English, I'm not a native speaker. If anyone could help me, that will be great.
Thanks.

var visible = true,
body = document.getElementById("body"),
mess = document.getElementById("message");
body.onclick = function() {
if (visible === true) {
mess.style.visibility = "hidden";
visible = false;
} else {
mess.style.visibility = "visible";
visible = true;
}
}
Edit Replaced body in selector as i didnt notice you wanted any part of the screen clicked

I'd suggest:
function toggleMessage(targetID){
var target = document.getElementById(targetID),
display = target.style.display;
target.style.display = display && display == 'block' ? 'none' : 'block';
}
document.body.addEventListener('click', function(){
toggleMessage('message');
});
Simple JS Fiddle demo.
Amended the above to use visibility (rather than display):
function toggleMessage(targetID){
var target = document.getElementById(targetID),
visibility = target.style.visibility;
target.style.visibility = visibility && visibility == 'visible' ? 'hidden' : 'visible';
}
document.body.addEventListener('click', function(){
toggleMessage('message');
});
Simple JS Fiddle demo.
References:
EventTarget.addEventListener().

Solution with jQuery (I recommend you to use display property. Because, if you use visibility, element will keep its space even it is hidden. With display: none; element is "removed".):
HTML
<div id="message"> Click! </div>
CSS
#message {
display: none;
}
jQuery
$(document).ready(function(){
$(window).click(function(){
$('#message').toggle();
});
});
DEMO: http://jsfiddle.net/j3KVT/2/
If you want to use visibility property then this is (one of many) solution with jQuery:
HTML
<div id="message">Click!</div>
jQuery
$(document).ready(function () {
$('#message').css('visibility', 'hidden');
$(window).click(function () {
if ($('#message').css('visibility') == 'hidden')
$('#message').css('visibility', 'visible');
else $('#message').css('visibility', 'hidden');
});
});
DEMO: http://jsfiddle.net/j3KVT/3/

Related

if mouseleave/ if click in Javascript

Is there a way in javascript to define what happens depending on if you just hover over an element or if you actually click it?
What I want to do is, for a button:
onmouseenter, the background-color is supposed to change.
If you just hover over it and leave the button again, the color is supposed to disappear.
If you click it, the color is supposed to "stay".
Is there a way to do this along the lines of if mouseout == true/ if click == true?
I tried looking it up but nothing really answered my question. Thank you very much in advance!
Edit: I definitely want to do it in Javascript, I'm aware of the fact that it can be easily done in CSS
Edit 2: This is what I tried:
var ifclick = false;
element.onclick = function() {
element.style.background = "pink";
element.style.borderColor = "pink";
ifclick = true;
};
if (ifclick == false) {
element.onmouseout = function() {
element.style.background = "white";
element.style.borderColor = "white";
};
}
else {
element.style.background = "pink";
element.style.borderColor = "pink";
};
element is the button whichever your mouse enters, ifclick is supposed to return "true" when the button is clicked, this the element.onmouseout function is ONLY supposed to if the button has not been clicked but for some reason (as stated below) the button is only pink as long as your mouse is still on the button and turns white as soon as you leave.
You can do this by using jQuery. Consider my code bellow:
<!DOCTYPE html>
<html>
<head>
<title>Button Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button id="btn">Text</button>
<script>
var persistence = false;
$( "#btn" ).mouseenter(function() {
$( this ).css("background-color", "yellow");
});
$( "#btn" ).click(function(event) {
$( this ).css("background-color", "yellow");
persistence = true;
});
$( "#btn" ).mouseleave(function(event) {
if( persistence === false){
$( this ).css("background-color", "inherit");
}
});
</script>
</body>
</html>
Taken from W3 School for mouse over.
<img onmouseover="bigImg(this)" src="smiley.gif" alt="Smiley">
Also Taken from W3 School for mouse click.
<body onmousedown="whichElement(event)">
Update
Based on what you said, you need a way of adding a .class when the mouse enters an area, and removing the .class when it leaves the area. Look into this.
<h1 onmouseover="style.color='red'" onmouseout="style.color='black'">Mouse over this text</h1>
Pure Javascript example,
window.onload = function() {
var htmlElement = document.getElementById("foo");
var clicked = false;
document.getElementById("foo").addEventListener("mouseover", function(){
if(!clicked) {
htmlElement.style.color = "red";
}
});
document.getElementById("foo").addEventListener("mouseout", function(){
if(!clicked) {
htmlElement.style.color = "black";
}
});
document.getElementById("foo").addEventListener("click", function(){
htmlElement.style.color = "red";
clicked = (clicked ? false : true);
});
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div id="foo">Hello!</div>
</body>
</html>
There is similarly a wide variety of DOM Events you can catch (Like onClick). Find most of them here.

How to change a checked event to an onclick event?

How I would change this simple function into an onclick event using a button, rather than a checkbox? I am really new to JavaScript.
function showhide() {
if (document.getElementById('toggle').checked == true) {
document.getElementById('hidethis').style.display = 'block';
} else {
document.getElementById('hidethis').style.display = 'none';
}
}
Better use with classList.toggle function .It toggle the className
function showhide() {
document.getElementById('hidethis').classList.toggle('hide');
}
.hide {
display: none;
}
<button onclick="showhide()">Click Me</button>
<div id="hidethis">Text</div>
Here's how, without using jQuery:
function showhide() {
var hidethis1 = document.getElementById('hidethis1');
var hidethis2 = document.getElementById('hidethis2');
if (getComputedStyle(hidethis1).getPropertyValue('display') === 'none') {
hidethis1.style.display = 'block';
hidethis2.style.display = 'none';
} else {
hidethis1.style.display = 'none';
hidethis2.style.display = 'block';
}
}
document.getElementById('clickthis').addEventListener('click', showhide);
#hidethis2 {
display: none;
}
<button id="clickthis">Click Me</button>
<div id="hidethis1">Hide Me (1)</div>
<div id="hidethis2">Hide Me (2)</div>
If you want to toggle more than two elements, you should give each of the elements the same class, and use a for loop.
<button id="yourbutton">Click</button>
<script type="text/javsacript">$("#yourbutton").on("click", function() {
if (document.getElementById('toggle').checked == true) {
document.getElementById('hidethis').style.display = 'block';
} else {
document.getElementById('hidethis').style.display = 'none';
}
});</script>
Hope it helps
And dont forget to include jquery plugin<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Easiest way to use jQuery
$(".buttonClass").click(function(){
$("#hidethis").toggleClass("displayNone");
})
//style code
.displayNone{ display: none;}

hide div when click outside

I am using a simple javascript code to toggle div onclick. You can see it in action on this link: k-prim.biz/Untitled-2.html - it is a quite simple demo page. What I want to make is to hide div not only when click on the "link" but also when click outside the div. Also how can I change the css style of the "link" when the div is displayed? Thank you in advance!
<script type="text/javascript" language="javascript">
function showHide() {
var ele = document.getElementById("showHideDiv");
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block"; }
}
</script>
<a href="#" onClick="return showHide();" >link</a>
<div id="showHideDiv" style="display:none;">hello!</div>
You've not given me any code to work with, so you'll have to modify this to suit your needs:
$(document).click(function() {
if(this != $("#the_div")[0]) {
$("#the_div").hide();
}
});
That will hide the div if a user clicks anywhere on the page that isn't that div.
HTML:
<div id="settings">
<input/><select></select><span>text</span>
</div>
Javascript:
var settings = document.getElementById('settings');
document.onclick = function(e){
var target = (e && e.target) || (event && event.srcElement);
var display = 'none';
while (target.parentNode) {
if (target == settings) {
display ='block';
break;
}
target = target.parentNode;
}
settings.style.display = display;
}
This is a quick hack I wrote. I am not sure why you want to do the same activity by clicking anywhere on the document. If you want to do that, replace jQuery('#link') with jQuery(document).
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
jQuery('#link').click(function(){
if(jQuery('#showHideDiv').hasClass('hide')) {
jQuery('#showHideDiv').removeClass('hide');
jQuery('#link').css('color', 'red');
} else {
jQuery('#showHideDiv').addClass('hide');
jQuery('#link').css('color', 'blue');
}
});
});
</script>
</head>
<body>
<a href="#" id="link" >link</a>
<div id="showHideDiv" class="hide">hello!</div>
</body>
</html>
This is the link to the jsfiddle
http://jsfiddle.net/EUScV/9/
and also add css rule
.hide {
display:none;
}

Hiding and Showing Elements with JavaScript or jQuery

I have an arrow on my site that I'd like if onclick, it hides one element, and shows another. Hitting it again, will hide the element that was shown and show the element that was hidden.
For example, I have
<div id="arrow">▾</div>
<div id="ad"></div>
<div id="description">Hidden</div>
<div id="nav">Also Hidden</div>
So at first, the ad is showing, and then one you've clicked the arrow, I'd like the ad to hide, and then unhide the description and nav.
With jQuery, use .toggle():
$("#arrow").click(function () {
$("#ad, #description, #nav").toggle();
});​
DEMO.
With plain JavaScript, you need to toggle the display property of each element manually:
document.getElementById("arrow").onclick = function () {
var description = document.getElementById("description");
var nav = document.getElementById("nav");
var ad = document.getElementById("ad");
if (ad.style.display == 'none') {
ad.style.display = '';
nav.style.display = 'none';
description.style.display = 'none';
} else {
ad.style.display = 'none';
nav.style.display = '';
description.style.display = '';
}
};​​​​​​
DEMO.
Try this (Since you asked for plain javascript)
window.onload=function(){
var arrow=document.getElementById('arrow').getElementsByTagName('a')[0];
arrow.onclick=function(){
var ad=document.getElementById('ad');
var description=document.getElementById('description');
var nav=document.getElementById('nav');
if(ad.style.display=='none')
{
ad.style.display='block';
description.style.display='none';
nav.style.display='none';
}
else
{
ad.style.display='none';
description.style.display='block';
nav.style.display='block';
}
return false;
};
};
DEMO.​
DEMO
​​ <input id="x" value="x" />
<input id="y" value="y" style="visibility:hidden" />
<input type="button" onclick="toggleBoth()" value="arrow" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
.
function toggle(id){
var elem = document.getElementById(id);
if(elem.style.visibility == 'hidden')
elem.style.visibility = 'visible';
else
elem.style.visibility = 'hidden';
}
function toggleBoth()
{
toggle('x');
toggle('y');
}
​

Javascript onclick event not firing on first click

The code below is a link which when clicked will open and close an initially hidden div. It works fine other than having to click the link twice in the first instance to open it. It's not a major problem but if it can be made so that the div opens on the first click that would be great.
toggleDiv.js
function toggleDiv(elem, eventType, handler) {
if (elem.addEventListener) {
elem.addEventListener(eventType, handler, false);
} else {
elem.attachEvent('on' + eventType, handler);
}
}
toggleDiv(window, 'load', function() {
var link = document.getElementById('myMagicLink'),
div = document.getElementById('foo');
toggleDiv(link, 'click', function() {
if (!link) return true;
if (div.style.display == "none") {
div.style.display = "block"
} else {
div.style.display = "none"
}
return true;
});
});
index.html
<body>
<a id="myMagicLink" href="http://www.google.com/">My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
<script language="JavaScript" type="text/javascript" src="toggleDiv.js"></script>
</body>
I had the same problem for toggling the display value of an ASIDE tag. Switching from "none" to "inline" and back again would not work on the first click. Display was set to "none" in my CSS file.
In my script I changed "none" to "" (which seems to mean "default" as far as I understand). The following code works fine for me now.
var x = document.getElementsByTagName("aside")[0];
if (x.style.display == "")
{
x.style.display = "inline";
}
else
{
x.style.display = "";
}
I understood this when I saw the CSS/actual values in Firefox developer tools: "aside" is shown with CSS attributes, but an "element" is first shown with no attribute. On first click, "element" was assigned a "display" attribute set to "none".
Not sure what the trouble you are having this... this works flawlessly for me in Chrome.
I did change the url of your link to reflect back to the same document, but the div foo is hiding and reappearing as it should.
Couple of style notes: Rather than setting display = "block" it is better to say display = "" so it can return to its default value.
In addition, I also included a preventDefault function. Your use of return true would work for DOM0 style event handling, but it did not work with the attachEvent/addEventHandler code. This properly keeps the link from being followed.
<html>
<head>
<title>Test</title>
<script>
function toggleDiv(elem, eventType, handler) {
if (elem.addEventListener) {
elem.addEventListener(eventType, handler, false);
} else {
elem.attachEvent('on' + eventType, handler);
}
}
toggleDiv(window, 'load', function() {
var link = document.getElementById('myMagicLink'),
div = document.getElementById('foo');
toggleDiv(link, 'click', function(e) {
if (!link) return cancelDefaultAction(e);
if (div.style.display == "none") {
div.style.display = "block"
} else {
div.style.display = "none"
}
return cancelDefaultAction(e);
});
});
function cancelDefaultAction(e) {
var evt = e ? e:window.event;
if (evt.preventDefault) evt.preventDefault();
evt.returnValue = false;
return false;
}
</script>
<body>
<a id="myMagicLink" href="#">My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
</body>
</html>
Sorry it seems a bit complicated for something pretty simple, unless you have a specific design in mind; but this should work equally well:
The Fiddle
<html>
<head>
<script language="JavaScript" type="text/javascript">
var toggled = false;
function toggleDiv()
{
if(toggled)
{
document.getElementById('foo').style.display = '';
toggled = false;
}
else
{
document.getElementById('foo').style.display = 'none';
toggled = true;
}
}
</script>
</head>
<body>
<a id="myMagicLink" href="http://www.google.com/" onClick='toggleDiv()'>My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
</body>
</html>
​

Categories

Resources