Remove Class if second click in pure Javascript - javascript

I'm trying to create a simple Lightbox like effect with pure Javascript. I'm trying to figure out how to remove the current class if clicked again. I've tried multiple solutions suggested on Stack Overflow without much success. I don't want to use jQuery or any additional plugins. I think the issue might be with my if/else statement, but can't seem to pinpoint the exact issue. http://jsfiddle.net/nFNG3/
document.addEventListener('DOMContentLoaded', init, false);
function init(){
function getPop() {
if (item.className.value == null ){
item.className += "" + newClass;
return createFrame();
}
else {
removeClass();
}
}
function createFrame() {
var el = document.createElement('iframe');
el.setAttribute('id', 'ifrm');
el.setAttribute('scrolling','no');
document.body.appendChild(el);
el.setAttribute('src', 'http://info.kinnser.com/WWW-DEMO-WEBFORM.html');
}
function removeClass() {
item.className.value == null;
}
var item = document.getElementById('popit');
var newClass = "light-background";
item.addEventListener('click', getPop, false);
}
HTML
<body>
<div id="container">
<div id="button-container">
Demo Now
<span id="working"></span>
</div>
</div>
</body>
CSS
.light-background{
position:fixed;
width:100%;
height:100%;
background-color:grey;
}
#ifrm{
position:fixed;
width:275px;
height:549px;
z-indez:4;
background-color:white;
top:20%;
left:50%;
margin-top:-50px;
margin-left: -100px;
overflow:hidden;
}

Hi do the changes as shown below
function getPop() {
if (!item.className){
item.className += "" + newClass;
return createFrame();
}
else {
removeClass();
}
}
function removeClass() {
item.className = '';
}
Hope this solves your problem

Related

How to Fade Out an element using Javascript

I have a loading page that I used javascript to make. I would like to be able to fade-out the loading page as the index.html fades in. I understand this can easily be done with jQuery, but would like to not use jQuery since I have yet to use it on this site. I understand this may be a common question, but I have not been able to tailor other answers to my solution since most use jQuery.
I am thinking to edit the opacity of the loading element onReady. Or could I do this with simple CSS?
Javascript:
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).style.display = value ? 'block' : 'none';
}
onReady(function () {
show('page', true);
show('loading', false);
});
HTML:
<div id="loading">
<div class="logo">
Logo
</div>
<span class="loading-center-cross"></span>
<h3>Loading...</h3>
</div>
<div id="page">
.....
</div>
I expect for the loading screen to fade to the index.html as previously described. Thanks for all the help!
You can do this with CSS, using something like the following:
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).classList.toggle('fade-in-out', value);
}
onReady(function () {
show('page', true);
show('loading', false);
});
And have the following CSS:
#page,
#loading {
transition: opacity 1s;
}
.fade-in-out {
opacity: 0;
pointer-events: none;
}
That way, the show() function will toggle a class of fade-in-out based on value, and there will be a transition to 'fade' the div in and out, with an addition of pointer-events: none to make the div non-interactive whist transitioning.

How to bring my element back after using display:none

On click I can hide my div element with display:none but can't get it back with display:inline when button is clicked
document.getElementById("red").onclick = function (){
document.getElementById("red").style.display = "none";
}
document.getElementById("back").onclick = function () {
document.getElementsById("red").style.display = "inline";
}
Hi your script has typo error.
getElementsById is having Elements instead of Element.
Alway use Console for error messages it will help you alot :).
Cheers !!!
Your script should look like this .
document.getElementById("red").onclick = function (){
document.getElementById("red").style.display = "none";
}
document.getElementById("back").onclick = function () {
document.getElementById("red").style.display = "inline";
}
Example: display:none to display:inline toggle.
document.getElementById("red").onclick = function (){
document.getElementById("red").style.display = "none";
}
document.getElementById("back").onclick = function () {
document.getElementById("red").style.display = "inline";
}
#red
{
color:#fff;
background:red;
padding:8px 20px;
}
<div id="red">RED (Click me)</div>
<button id="back">Back</button>
You can always see the errors in the console and figure out the solution.
I would advise you to use a class for styling and also use Element.addEventListener() for the events.
var red = document.getElementById('red')
var back = document.getElementById('back')
red.addEventListener('click', function() {
this.classList.add('hidden')
})
back.addEventListener('click', function() {
red.classList.remove('hidden')
})
https://jsfiddle.net/cnzabf1a/
Documentation on:
addEventListener
classList
If your're using flex using 'inline-flex' may be better:
document.getElementById("red").style.display = "inline-flex";

How can i save state my button after refresh?

I have this sample:
link
CODE HTML:
<div class="square">
</div>
CODE CSS:
.square{
width:20px;
height:20px;
background:green;
}
.fa-square{
background:red;
width:20px;
height:20px;
}
CODE JS:
$("div").click(function(){
if ( $( this ).hasClass( "fa-square" ) ) {
$( this ).removeClass('fa-square').addClass('square');
}else{
$('.square').removeClass('square').addClass('fa-square');
}
});
What I want to do is simply believe ...
I want to save the state after refresh the page button
For example ... if the button is green and is ... then remain green refresh after refresh
If the button is red, red remain after refresh.
How can you do that?
Anyone can show me a simple example?
Thanks in advance!
You can set cookies and read them at the beginning of the content to check if a state is set like this fiddle
function readCookie(name) {
return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{} ()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];
}
if(readCookie('state') == "fa-square"){
$('div').addClass('fa-square');
}else if(readCookie('state') == "square"){
$('div').addClass('square');
}
$("div").click(function () {
if ($(this).hasClass("fa-square")) {
$(this).removeClass('fa-square').addClass('square');
document.cookie= "state=square";
} else {
$('.square').removeClass('square').addClass('fa-square');
document.cookie= "state=fa-square";
}
});
var retrievedObject = localStorage.getItem('class');
if(retrievedObject){
$('div').addClass(retrievedObject)
}
console.log('class ', (retrievedObject));
$("div").click(function () {
if ($(this).hasClass("fa-square")) {
$(this).removeClass('fa-square').addClass('square');
localStorage.setItem('class', 'square');
} else {
$('.square').removeClass('square').addClass('fa-square');
localStorage.setItem('class', 'fa-square');
}
});
This one utilizes the localstorage to store the value of class then on onload give the stored class to the div
DEMO
Try this example using localStorage
$(function() {
var cls = 'state'; //key name for local storage
var sqr = $('.square');
sqr.addClass(localStorage.getItem(cls)); //restore state on page load
sqr.on('click', function() {
sqr.toggleClass('fa-square'); //shorthand for add/remove class
localStorage.setItem(cls, this.className); //preserve current state on every click
});
});
.square {
width: 20px;
height: 20px;
background: green;
}
.fa-square {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="square"></div>

javascript print code is not working properly

My java script print code is not working properly. I have this code is dialog box. when user clicks on print button I am calling print() function.
The problem I am facing when My print section is opening in Chrome data and table are not coming fine in preview.
I tried to implement this code here
HTML code:
<div class="modal-body">
<div class="" id="mydata">
<div id="grid">Some Data</div>
</div>
</div>
<button type="button" id="outageSummary_printBtn" class="btnPrint" data-dismiss="modal" onclick="print()>Print</button>
JS Code :
function print(data, event) {
event.preventDefault();
printElement(document.getElementById("grid"));
};
function printElement (elem) {
var domClone = elem.cloneNode(true);
var $printSection = document.getElementById("grid");
if (!$printSection) {
var $printSection = document.createElement("div");
$printSection.id = "grid";
document.body.appendChild($printSection);
} else {
$printSection.innerHTML = "";
$printSection.appendChild(domClone);
}
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if (is_chrome == true) {
window.print();
if (window.stop) {
location.reload(); //triggering unload (e.g. reloading the page) makes the print dialog appear
window.stop(); //immediately stop reloading
}
} else {
window.print();
}
return false;
};
CSS Code:
#media screen {
#grid {
/*display: none;*/
}
}
#media print {
body * {
visibility:hidden;
}
#grid, #grid * {
visibility:visible;
}
#grid {
position:absolute;
left:0px;
top:0px;
}
}
I checked lot of print functionality, but I am not able to get this issue. I believe this is related to CSS or when I am adding Html element.
Please Guide !!
Unfortunately I cannot post as a comment, but do you mean that it shows correctly in the preview, but not on the webpage?
(Also from the code you've posted, it seems you're missing the below [or an onclick function on the button]:
document.getElementById("outageSummary_printBtn").onclick = function () {
printElement(document.getElementById("grid"));
};
Sorry if you've deliberately left this out in the snippet)

javascript delay popup

im having a prob with javascript which has been bugging me for hours now. I need to delay a css popup so that if you just scroll mouse around page you wont get loads of popups.
Whatever i try it either makes the popup act goofy, poping up after x seconds with a swipe of any link, auto closing etc etc. if i add a timer to the mouseover it starts acting weird, if i then delete the timer for mouseout it works fine but you can no longer mouseover menu before it closes, also tried adding negative margin and it autocloses
cheers all
javscript
<script type="text/javascript">
var span = document.querySelectorAll('.pop');
for (var i = span.length; i--;) {
(function () {
var t;
span[i].onmouseover = function () {
hideAll();
clearTimeout(t);
this.className = 'popHover';
};
span[i].onmouseout = function () {
var self = this;
t = setTimeout(function () {
self.className = 'pop';
}, 300);
};
})();
}
function hideAll() {
for (var i = span.length; i--;) {
span[i].className = 'pop';
}
};
</script>
css
.pop {
position:relative;
}
.pop div {
display: none;
}
.popHover {
position:absolute;
}
.popHover div {
background-color:#FFFFFF;
border-color:#AAAAAA;
border-style:solid;
border-width:1px 2px 2px 1px;
color:#333333;
padding:5px;
position:absolute;
z-Index:9999;
width:150px;
display: inline-block;
margin-top: -20px;
}
Using jquery might be a little more helpful for what you are trying to do. Try something like this:
// Use a CDN to take advantage of caching
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var t;
$('.pop').on('mouseover', $.proxy(function () {
hideAll();
clearTimeout(t);
this.addClass('popHover');
this.removeClass('pop');
}, this));
$('.pop').on('mouseout', $.proxy(function () {
var self = this;
t = setTimeout(function () {
self.addClass('pop');
self.removeClass('popHover');
}, 300);
},this));
function hideAll() {
// Since you are calling this from the mouseover function of all the
// elements with the 'pop' class, I dont understand what the purpose of this class
// is so it might not be entirely correct.
$('.pop').addClass('pop');
}
</script>
Let me know if this helps. If you still need it. It would be helpful to have a fiddle to maybe tweak to give you a more accurate response.

Categories