Make id ex disappear if you click anywhere outside of it - javascript

I'm trying to figure out how I can make a targeted element disappear. If you click any where that is outside of that element. I have created a toggle effect with a button but I want to also hide id ex if there is any clicks outside of ex. I have
found working sources on this subject but it's based on jQuery most of the time. I have nothing against jQuery I just need to do this in pure JS structure for
personal reasons.
<!DOCTYPE html>
<html>
<head>
<style>
#ex{
display: none;
}
</style>
<script>
document.addEventListener('DOMContentLoaded',function(){
var b= document.getElementsByTagName('button')[0];
b.addEventListener('click',fx);
function fx() {
var x = document.getElementById("ex");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
});
</script>
</head>
<body>
<button>Toggle</button>
<h1 id="ex">Blablablablabla bla bla JS</h1>
</body>
</html>
UPDATE
Any time I tried to ask this question on this topic on many sites nobody never understand what I mean. In other words I don't want the body to do any toggling just the button the best way I can explain this is like this you know how in some applications if you click on a drop down menu and you click out side of that drop down menu then it disappears but you can use the navigation bar button to bring it back? That's what i'm trying to do .
I want something like this but in pure JS structure.
<style>
#ex{
display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#ex').click(function(execute){
execute.stopPropagation();
});
$('button').click(function(execute) {
execute.preventDefault();
execute.stopPropagation();
$('#ex').toggle();
});
$(document).click(function() {
$('#ex').hide();
});
});
</script>
<button>Toggle</button>
<h1 id='ex'>Blablablablabla bla bla JS</h1>

<!DOCTYPE html>
<html>
<head>
<style>
#ex{
display: none;
}
</style>
<script>
document.addEventListener("click", function(obj){
var x = document.getElementById("ex");
if(obj.target.id != "ex") {
if (x.style.display === "block") {
x.style.display = "none";
} else if(obj.target.id == "btn") {
x.style.display = "block";
}
}
});
</script>
</head>
<body>
<button id="btn">Toggle</button>
<h1 id="ex">Blablablablabla bla bla JS</h1>
</body>
</html>

Update
You can save the button id and compare it with the clicked element id.
var b= document.getElementsByTagName('button')[0];
var btnId = b.getAttribute('id');
document.addEventListener('click',fx);
function fx(e) {
var x = document.getElementById("ex");
if (e.target.getAttribute('id') == btnId) {
if(x.style.display == "block")
x.style.display = "none";
else
x.style.display = "block";
}
else{ // we did not click on button
if (e.target.getAttribute('id') != 'ex')
x.style.display = 'none';
}
}

Related

How can I use a boolean to toggle an images visibility?

I'm trying to use a single button to toggle between an image being visible and invisible. I want the first click to make the image appear, and the second to hide it again. I figured using a boolean would be the best way to do this, but I can't quite get it to work.
function myStats(){
counter = true;
if(counter == true){
document.getElementById('stat').style.display = 'block';
}
if(counter == false){
document.getElementById('stat').style.display = 'none';
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color: #A9A9A9;}
</style>
</head>
<body>
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:none;"/></center>
<button onclick="myStats()">Player 1</button>
<h3 id="var"></h3>
</body>
</html>
I realize this will obviously not work because I'm not toggling the boolean, but that's what I'm looking for help with.
Create a css class called hidden, then use classList.toggle(). When the button is clicked toggle the class on the image.
It can be done like this:
document.querySelector('button').addEventListener('click', myStats)
function myStats() {
document.getElementById('stat').classList.toggle('hidden')
}
.hidden { display: none; }
<center><button>Player 1</button></center>
<center><img id="stat" src="https://via.placeholder.com/150" class="hidden"></center>
I edited your snippet to put a toggle on there and made it so the function myStats() doesn't set counter = true everytime you click it. Seems to work fine. I also hoisted the declaration of the counter variable above that function declaration, since that's where your toggle should be, represented by counter = !counter.
let counter = true;
function myStats(){
counter = !counter;
if(counter == true){
document.getElementById('stat').style.display = 'block';
}
if(counter == false){
document.getElementById('stat').style.display = 'none';
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color: #A9A9A9;}
</style>
</head>
<body>
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:none;"/></center>
<button onclick="myStats()">Player 1</button>
<h3 id="var"></h3>
</body>
</html>
Boolean variable should be outside of the function so its value won't reset every time you called a function. Also you should toggle this boolean variable value from true to false and vise versa. Check out my solution. Hope this helps!
var isImageShouldBeVisible = true;
function toggleImageVisibility() {
isImageShouldBeVisible = !isImageShouldBeVisible;
if (isImageShouldBeVisible) {
document.getElementById('stat').style.display = 'block';
} else {
document.getElementById('stat').style.display = 'none';
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color: #A9A9A9;}
</style>
</head>
<body>
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:block;"/></center>
<button onclick="toggleImageVisibility()">Player 1</button>
<h3 id="var"></h3>
</body>
</html>
This is because counter remains same throughout the code. You need to add counter = !counter at end of you function. I would do it using ternary operators. There is need of Boolean just check the style.display
let elm = document.getElementById('stat');
function myStats(){
let {display} = elm.style;
elm.style.display = display === 'none' ? 'block' : 'none';
}
body{background-color: #A9A9A9;}
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:none;"/></center>
<button onclick="myStats()">Player 1</button>
<h3 id="var"></h3>

Toggle Hide/show upon clicking a checkbox and hitting submit button javascript

I am trying to use checkboxes and a submit button to toggle hide/show a section of my resume. I have two sections, education and work experience. I have the code to set up the checkboxes and submit button but I am not sure how to code what comes after it to make the checkboxes work. this is what I have:
<script>
function validateCheckbox() {
var checkbox = document.getElementsByName("c1");
for (var i=0; i < checkbox.length; i++) {
if (radios[i].checked) {
return true;
}
}
function myFunction() {
var x = document.getElementById("workexperience");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
I want to toggle the visibility of an element by id in CSS and I want to have the information be hidden upon page load so that if a site visitor clicks on the checkbox that says work experience and then hits the submit button it will show the relevant section either education for one checkbox or work experience for the other.
HTML
<div id="wrapper">
<div>
<input type="radio" name="resume" value="work-experience">
<input type="radio" name="resume" value="education">
<button type="button" id="view-resume">View</button>
</div>
<div id="work-experience" class="display-none">Work Experience</div>
<div id="education" class="display-none">Education</div>
</div>
CSS
<style type="text/css">
.display-none{
display: none;
}
</style>
JAVASCRIPT
<script type="text/javascript">
document.getElementById('view-resume').addEventListener("click", function(){
var resume = document.querySelector('input[name = "resume"]:checked').value;
document.getElementById(resume).style.display = 'block';
if(resume == 'work-experience'){
document.getElementById('education').style.display = 'none';
}else{
document.getElementById('work-experience').style.display = 'none';
}
});
</script>

how do I use the same link to "re-hide" previously hidden text via Javascript?

The below code snippet shows the invite code when I click "Invite Code". But how do I re-hide the invite code if the same link is clicked again? And can it be done where it cycles back and forth with subsequent clicks? I didn't write this code but merely modified it to my use. I am still very new to this type of thing. Thanks!
<style>
div.hide { display:none; }
div.show { text-align:center; }
</style>
<script type='text/javascript'>
function showText(show, hide) {
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
</script>
<br>
<font color="red">-</font>Home<font color="red"> / </font><a onclick="showText('text1')" href="javascript:void(0);">Invite Code</a>-</font>
<div id="text1" class="hide"><font color="red">abc123</font></div>
</center></h3>
Simply use this function:
function showText(id)
{
var elem = document.getElementById(id);
if(elem.style.display == 'none')
{
elem.style.display = 'inline';
}
else
{
elem.style.display = 'none';
}
}
<a onClick="showText('text1');" href="#">Show or Hide</a><br/>
<div style="height: 30px;"><div id="text1" style="display: none;">Text to hide or show... WTF?!</div></div>
<div>This text should not move.</div>
PS: This also works for 2 Elements...
Greetings
I really don't see the use for the show class. You could just toggle the hide class on the elements that you want to toggle.
Assume you dont need the show class, then use the classList.toggle function like this
function toggle(target){
document.getElementById(target).classList.toggle('hide');
}
.hide{ display:none }
<button onclick="toggle('test')">Show / Hide</button>
<div id="test" class="hide">Hello world!</div>
save the state with a boolean
var hided = true;
function showText(show,hide){
if (hided){
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
else{
document.getElementById(show).className = "hide";
document.getElementById(hide).className = "show";
}
hided = !hided;
}
fiddle with this code and some of your html : fiddle,
isn't it the expected behavior ?
<html>
<div ID="content" style="display:block;">This is content.</div>
<script type="text/javascript">
function toggleContent() {
// Get the DOM reference
var contentId = document.getElementById("content");
// Toggle
contentId.style.display == "block" ? contentId.style.display = "none" :
contentId.style.display = "block";
}
</script>
<button onclick="toggleContent()">Toggle</button>
</html>
//Code is pretty self explanatory.

Toggling multiple divs with one link Javascript

so, ive got 2 divs, one which is visible from start, and the other is hidden. Im trying to work out the action so that when i click a single link, the first div disappears and the second appears, and to reverse on second click. I have some knowledge of javascript, but zero knowledge of Jquery and those were the only questions i could find on here.
<script language="javascript">
function toggle() {
var ele = document.getElementById("toggleContent");
var text = document.getElementById("displayContent");
if(ele.style.display == "block") {
ele.style.display = "none;
text.innerHTML = "blog posts";
}
else {
ele.style.display = "block";
text.innerHTML = "hide posts";
}
}
</script>
this is what i have so far, which works for one div, but i dont know how to change this to work for 2 divs through the same link
You are missing a quote, add a second quote like below:
ele.style.display = "none";
Use a class rather than an ID.
<style type="css/stylesheet">
#div1 {
width:200px;
height:100px;
background:green;
}
#div2 {
width:200px;
height:100px;
background:red;
}
.toggle {
display:none;
}
</style>
<div id="menu">Toggle
</div>
<div id="div1" class="toggle">
<p class="displayContent">I'm some content 1</p>
</div>
<div id="div2" class="toggle">
<p class="displayContent">I'm some content 2</p>
</div>
<script language="javascript">
var a = document.getElementById("link");
a.onclick = function () {
var ele = document.getElementsByClassName("toggle");
for (var i = 0; i < ele.length; i++) {
var item = ele[i];
if (item.style.display == "block") {
item.style.display = "none";
} else {
item.style.display = "block";
item.innerHtml = "some content from " + i;
}
}
};
</script>
Here is the JSFiddle solution http://jsfiddle.net/dUU7j/

Use link click to clear input field Javascript

I am trying to use a link to clear a text input field. I am hiding and showing a memo field and and if the user puts text in the field and clicks "remove memo" link I want to text field to clear on click.
<html>
<head>
<script language="JavaScript">
function toggle(id) {
var state = document.getElementById(id).style.display;
if (state == 'block') {
document.getElementById(id).style.display = 'none';
} else {
document.getElementById(id).style.display = 'block';
}
}
oldTextAry = new Array();
function changeText (fieldObj, newTexStr) {
if (newTexStr == fieldObj.innerHTML) {
fieldObj.innerHTML = oldTextAry[fieldObj.id];
} else {
oldTextAry[fieldObj.id] = fieldObj.innerHTML;
fieldObj.innerHTML = newTexStr;
}
}
</script>
<style type="text/css">
<!--
#hidden1 {display: none;}
-->
</style>
</head>
<body>
<a href="###" onclick="toggle('hidden1'); changeText(this,'Remove Memo');" class="memo" >Add Memo</a>
</div>
<div id="hidden1"><div class="memo">Memo: <input type="text" id="ctlWorkflow_ctlMemo381" size="45" maxlength="32" name="ctlWorkflow:ctlMemo381"></div> </div>
</body>
</html>
I am stuck and cannot get the field to clear.
Use the below code in the click delegate. Sorry for the mistaken answer.
document.getElementById("ctlWorkflow_ctlMemo381").value = '';
Cheers

Categories