how to make javascript object disappear when click on rest of page - javascript

How to change the following code so when clicking anywhere on the web page, the line "This is foo" will disappear, right now I have to click "Click here" to make it disappear.
<html>
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>
<body>
Click here
<div id="foo">This is foo</div>
</body>
</html>

You'll need to bind the click event to the body element for it to fire when you click anywhere on the page.

Try to use document object for attaching event handler
document.onclick = function(){
var e = document.getElementById('foo');
e.style.display = ((e.style.display != 'none') ? 'none' : 'block');
};

HTML:
<body onclick="foo();">
Click here
<div id="foo" style="display:none;" >This is foo</div>
</body>
JS:
var b = false;
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
b = true;
}
function foo() {
var e = document.getElementById('foo');
if(!b) e.style.display = 'none';
b=false;
}
And this bit of css:
body,html
{
width:100%;
height:100%;
}
http://jsfiddle.net/57ZpS/8/

Related

execute javascript after css class change

I am using this code to hide a div whenever I click a button. I am trying to activate this function not on 'onclick' but whenever the button gets the class 'active'.
Is that possible?
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
Though, not sure how the element's class is changing, you can try calling the function if element has the class using classList.contains().
The following example demonstrate that along with MutationObserver and setInterval():
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "block" || x.style.display === '') {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
var elem = document.getElementById("tryBtn");
let observer = new MutationObserver(mutationRecords => {
if(elem.classList.contains('active')){
myFunction();
}
});
// observe attributes
observer.observe(elem, {
attributes: true
});
// test
setInterval(function(){
if(elem.classList.contains('active')){
elem.classList.remove('active');
}
else{
elem.classList.add('active')
}
}, 1000);
<button id="tryBtn">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
What you probably want to do is to use the MutationObserver API
<div id="myDIV">
This is my DIV element.
</div>
<button id="myButton" onclick="changeClass()">Change class</button>
<script>
function changeClass() {
document.getElementById("myDIV").classList.add("active");
console.log("Changed class to active")
}
function myFunction() {
var x = document.getElementById("myDIV");
console.log(x.style.display);
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
const config = {attributes: true};
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for(let mutation of mutationsList) {
if (mutation.attributeName === 'class') {
if(mutation.target.className.includes("active")){
myFunction(); // Or you can put function code here.
}
}
}
}
//Set the target node you want to observe
const targetNode = document.getElementById('myDIV');
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
</script>
I used the changeClass function so you can see how this works. Since I suppose you already have some way of setting the class to "active"

Having trouble making an image disappear when using onmouseover event on a button

I'm having trouble making an image disappear while using an onmouseover event not on it, but on a button element. I need it to appear while onmouseover and disappear while not onmouseover. Heres my code:
<script>
function sfunc1() {
var x = document.getElementById('imgSWTCH1');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
function sfunc2() {
var x = document.getElementById('imgSWTCH2');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
function sfunc3() {
var x = document.getElementById('imgSWTCH3');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
function sfunc4() {
var x = document.getElementById('imgSWTCH4');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
function sfunc5() {
var x = document.getElementById('imgSWTCH5');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
function sfunc6() {
var x = document.getElementById('imgSWTCH6');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
function sfunc7() {
var x = document.getElementById('imgSWTCH7');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
This is the javascript to make it appear on mouseover, and the html is
<img id="imgSWTCH1"src="https://www.shareicon.net/data/128x128/2016/10/20/846459_blue_512x512.png" width="100" height="100"/>
<img id="imgSWTCH2"src="https://www.writeraccess.com/wp-content/uploads/2014/08/blog-html-5.png" width="100" height="100"/>
<img id="imgSWTCH3"src="https://www.shareicon.net/data/128x128/2016/06/25/619190_java_256x256.png" width="100" height="100"/>
<img id="imgSWTCH4"src="https://www.shareicon.net/data/128x128/2016/05/06/760855_css_512x512.png" width="100" height="100"/>
<img id="imgSWTCH5"src="http://poiemaweb.com/img/socketio-logo.png" width="100" height="100"/>
<img id="imgSWTCH6"src="https://www.shareicon.net/data/128x128/2016/07/08/116973_development_512x512.png" width="100" height="100"/>
<img id="imgSWTCH7"src="https://www.shareicon.net/data/128x128/2015/08/30/93000_javascript_512x512.png" width="100" height="100"/>
<center>
<br />
<br />
<table >
<tb id="tab" onmouseover="sfunc1()" onmouseout="this.className='BO';">C</tb>
<br />
<tb id="tab" onmouseover=" sfunc3()" onmouseout="this.className='BO';">Java</tb>
<tb id="tab" onmouseover=" sfunc2()" onmouseout="this.className='BO';">HTML</tb>
<tb id="tab" onmouseover="sfunc4()" onmouseout="this.className='BO';">CSS</tb>
<tb id="tab" onmouseover="sfunc5()" onmouseout="this.className='BO';">Socket.io/Node</tb>
<tb id="tab" onmouseover="sfunc6()" onmouseout="this.className='BO';">Angular.js</tb>
<br />
<tb id="tab" onmouseover="sfunc7()" onmouseout="this.className='BO';">Javascript</tb>
<tb id="tab" onmouseover=" this.className='BC';" onmouseout="this.className='BO';">and much more!</tb>
</table>
</center>
The onmouseout for all of these just makes the background orange but I want it to make the image corresponding to it disappear, which I'm having trouble with since you cant assign multiple ID's to an element. A jquery solution would work too, and so would one in angular.
https://plnkr.co/edit/WwpzOkipsiCrbgbpXbd4?p=preview
heres the pnlkr link, stetch the html portion out to see the whole thing too.
Here is a simple example using JQuery:
https://jsfiddle.net/ztuf96dg/4/
$(document).ready(function() {
$('li').hover(function(e) {
var imageID = $(e.currentTarget).attr('data-img-id');
var $image = $('img[data-img-id="' + imageID + '"]');
$image.show();
},
function(e) {
var imageID = $(e.currentTarget).attr('data-img-id');
var $image = $('img[data-img-id="' + imageID + '"]');
$image.hide();
});
});
Try doing it with one function for mouseover and one for mouseout. Also use the visibility property of the img instead of display to prevent the elements jumping.
See it here:
https://plnkr.co/edit/YeOgtFeEmNhRCgdQ0Mlp?p=preview
EDIT
So the point is:
function sfuncOver(imgId) {
var x = document.getElementById(imgId);
if (x.style.visibility === 'hidden') {
x.style.visibility = 'visible';
} else {
x.style.visibility = 'hidden';
}
}
function sfuncOut(imgId) {
var x = document.getElementById(imgId);
x.style.visibility = 'visible';
}
...in js and in html:
<td id="tab1" onmouseover="sfuncOver('imgSWTCH1')" onmouseout="sfuncOut('imgSWTCH1')">C</td>
...and so on. BUT doing this with jQuery would be 10 thousands better :) This is the coding style of the 90s :)
You have 7 functions doing the same exact thing. A better approach may be to create one function and bind what element you want to hide to it. Here is a fiddle with an example: https://jsfiddle.net/83drj2rs/1/
Here is the corresponding JavaScript:
function toggleVisibility(element){
if(element.style.display === "none") {
element.style.display = "inline-block";
} else {
element.style.display = "none";
}
}
Array.prototype.slice.call(document.getElementsByClassName('tab')).forEach(function(element){
element.onmouseover = toggleVisibility.bind(this, document.getElementById(element.getAttribute('data-hide')));
});
Also note that I removed all of your onmouseover attributes on the html elements themselves and replaced them with a data-hide attribute instead. This tells the function which element to hide on the mouseover event.
Try something like this:
HMTL:
<table >
<tb id="tab1">C</tb> //make sure id is unique for each <tb>
<br />
(...)
</table>
Javascript:
(*)make sure you wrap javascript on document ready.
$(function() {
$('#imgSWTCH1').hide();
$('#tab1').mouseover(function (e) {
//e.stopPropagation();
$('#imgSWTCH1').show();
});
$('#tab1').mouseout(function (e) {
//e.stopPropagation();
$('#imgSWTCH1').hide();
});
});
var change=function(){
if(document.getElementById("image").style.visibility == "visible"){
document.getElementById("image").style.visibility = "hidden";}else{document.getElementById("image").style.visibility="visible";}
}
function enter(){
document.getElementById("image").style.visibility = "hidden";
}
function leave(){
document.getElementById("image").style.visibility="visible";
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'/>
<script src='script.js'></script>
</head>
<body>
<img onmouseover="enter();" onmouseout="leave();" id="image" src="https://publicdomainvectors.org/photos/Microscope-BW.png"/>
<button onclick="change();" >ClicMe</button>
</body>
</html>
Run the code snnipet
Hope it does it...Good Luck

On click show 'Div 1' & hide 'Div 2' & On click of same button show 'Div 2' and hide 'Div 1'?

I am able do this functionality with different button. but i am not able achieve this on click of same button.
Any help/suggestions
Thanks
Toggle the current element using ternary-operator
Use Element.style.display to set the display css
property
var btn = document.getElementById('btn');
var curr = 'div2';
btn.onclick = function() {
document.getElementById(curr).style.display = 'none';
curr = curr === 'div2' ? 'div1' : 'div2';
document.getElementById(curr).style.display = 'block';
};
div {
display: none;
}
<div id="div1">#div1</div>
<div id="div2">#div2</div>
<button id='btn'>Change</button>
Anything like this?
function divchange(){
div1 = document.getElementById("div1");
div2 = document.getElementById("div2");
if(div1.style.display == "none"){
div1.style.display = "block";
div2.style.display = "none";
}else{
div1.style.display = "none";
div2.style.display = "block";
}
}
<button id="divchangebutton" onclick="divchange();">test</button>
<div id="div1">asdf</div>
<div id="div2" style="display:none;">qwert</div>
Problem - If "display:none" sets in css, we cannot get value. "elem.style.display" return empty string.
We can solve it, using Computed Style.
var btn = document.getElementById("btn-toggle");
btn.addEventListener("click", function(){
var one = document.querySelector(".one");
var tow = document.querySelector(".tow");
one.style.display = (getRealDisplay(one) == 'none') ? 'block' : 'none';
tow.style.display = (getRealDisplay(tow) == 'none') ? 'block' : 'none';
});
// get real value of 'display' property
function getRealDisplay(elem) {
if (elem.currentStyle) {
return elem.currentStyle.display;
} else if (window.getComputedStyle) {
var computedStyle = window.getComputedStyle(elem, null);
return computedStyle.getPropertyValue('display');
}
}
.one, .tow{
width:200px;
min-height: 200px;
background-color:burlywood;
}
.tow{
display: none;
background-color:cadetblue;
}
<div class="one">1</div>
<div class="tow">2</div>
<button id="btn-toggle">show hide</button>

Showing and Hiding divs with Javascript

Here's my code:
<script>
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'none') {
document.getElementById('id + x').innerText = '[-]';
e.style.display = 'block';
}
else {
document.getElementById('id + x').innerText = '[+]';
e.style.display = 'none';
}
}
</script>
[+]
<div id="httpserver" style="display:block;">
....my content...
</div>
When I click the + nothing happens. I will eventually have multiple divs, each specifically named, so this function needs to be able to handle all the divs.
Any help is appreciated!
First you have to change your HTML. You have to add "" when you pass the value.
Change
onclick="toggle_visibility(httpserver);"
to
onclick="toggle_visibility('httpserver');"
HTML:
[+]
<div id="httpserver" style="display:none;">
....my content...
</div>
And then change
document.getElementById('id + x').innerText
to
document.getElementById(id + 'x').innerText
You should pass the var id appended with the char x but you pass the id+x as a char
JS:
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'none') {
document.getElementById(id + 'x').innerText = '[-]';
e.style.display = 'block';
}
else {
document.getElementById(id + 'x').innerText = '[+]';
e.style.display = 'none';
}
}
DEMO
I think you need this:
First you need to change markup with following
onclick="toggle_visibility('httpserver');" // Wrap id with ''
As there was some quotes error in js too look for the comments in the below:
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'none') {
document.getElementById(id + 'x').innerText = '[-]'; // Miss placed quotes ' with id and x
e.style.display = 'block';
} else {
document.getElementById(id + 'x').innerText = '[+]'; // Miss placed quotes ' with id and x
e.style.display = 'none';
}
}
Fiddle
You can accomplish this in a more concise and easier fashion using CSS and simply toggling a class via JS. Css content can swap out the + or - as well as show/hide the relevant contents.
.collapsible .toggle:before { content: '[+]' }
.collapsible.opened .toggle:before { content: '[-]' }
.collapsible .contents { display: none }
.collapsible.opened .contents { display: block }
$('.collapsible').on('click','.toggle',function() {
$(this).parent().toggleClass('opened');
});
<section class="collapsible"><a class="toggle" data-contents="part1">Part1</a><div class="contents" id="contents-part1">This is the expand/collapse content.</div></section>
<section class="collapsible"><a class="toggle" data-contents="part2">Part2</a><div class="contents" id="contents-part2">This is the expand/collapse content.</div></section>
http://jsfiddle.net/YG3kK/

Catch img tag and change image

I have one problem with javascript code. I know how to do using jQuery but I must use js for this. I need when someone click on first div to catch image "show.png" in first div and change it with another
I have HTML code like this (this repeat couple time with different ID)
<div class="clickdown" onclick="return toggleMe('p_202')">
<table>
<tr valign="top">
<td width="20px">
<img src="images/show.png" align="top" alt="" />
</td>
<td>
<b>textttext</b> <img src="images/btn_New.png" alt="" />
</td>
</tr>
</table>
</div>
<div id="p_202" class="clickdown_content" style="display: none;">
<p>
texttexttexttexttexttexttext
</p>
</div>
and exist Javascript code for expand and colapse second div.
function toggleMe(a) {
var e = document.getElementById(a);
if (!e) return true;
if (e.style.display == "none") {
e.style.display = "block"
} else {
e.style.display = "none"
}
return true;
}
FYI Don't tell me "This code are a..ul" - I know it but I have request just to add, not to change any.
So I can't add ID and use this with getElementByID()
I try something like this but that don't work (Here I'm hiding image just to see does ti work)
function toggleMe(a) {
var ttable = document.getElementsByTagName("table").item(0);
var ttr = ttable.getElementsByTagName("tr").item(0);
var ttd = ttr.getElementsByTagName("td").item(0);
vari = ttd.getElementsByTagName("img").item(0);
if (i.src == "images/btn_New.png") {
i.style.display == "none"
} else {
i.style.display = "block"
};
var e = document.getElementById(a);
if (!e) return true;
if (e.style.display == "none") {
e.style.display = "block"
} else {
e.style.display = "none"
}
return true;
}
Resume:
I must leave old code html and javascript and add new javascript code
It works:
function toggleMe(a) {
var ttable = document.getElementsByTagName("table").item(0);
var ttr = ttable.getElementsByTagName("tr").item(0);
var ttd = ttr.getElementsByTagName("td").item(0);
var i = ttd.getElementsByTagName("img").item(0);
if (i.src.indexOf("images/show.png") !== -1) {
i.style.display = "none";
} else {
i.style.display = "block";
}
var e = document.getElementById(a);
if (!e) return true;
if (e.style.display == "none") {
e.style.display = "block";
} else {
e.style.display = "none";
}
return true;
}
You have to use indexOf because in attribute src you have the whole url.
Plunker example
Image you can easy change in this way:
i.src = "images/newShow.png";

Categories