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>
Related
I have a div that gets filled dynamically when the user sends data from form, it is similar to chat box. where the user ends message and that message gets displayed inside the div. Now this div has a scroll bar that should stay at the bottom but if the user scrolls then it should stay at that position where the user has kept it
The issue is that although the scroll bar stays at the bottom but when the user pulls it up, then also it pulls itself to bottom and the user can't use it to scroll.
Code for div
var youInterval;
function startInterval() {
youInterval = setInterval(function() {
var elem = document.getElementById('scrollbody');
elem.scrollTop = elem.scrollHeight;
}, 500);
}
document.addEventListener('scroll', function(event) {
if (event.target.id === 'scrollBottom') {
clearInterval(youInterval);
}
}, true);
startInterval();
.chatbox__body {
overflow-y: auto;
}
<div class="chatbox__body" id="scrollbody"></div>
Can anyone please help me with the issue
Your condition here is failing if (event.target.id === 'scrollBottom') {
The event generated by scroll is on document so, event.target.id is actually checking id property of document which is not there.
You have to disable overflow in body first and then add overflow to div
html,body{ height:100%; width:100%;overflow:hidden;}
.chatbox__body {
overflow-y: auto;
height:100%;
}
In your JS check for if (event.target.id === 'scrollbody') {
SNIPPET
var youInterval;
function startInterval() {
youInterval = setInterval(function() {
var elem = document.getElementById('scrollbody');
elem.scrollTop = elem.scrollHeight;
}, 500);
}
document.addEventListener('scroll', function(event) {
debugger;
if (event.target.id === 'scrollbody') {
clearInterval(youInterval);
}
}, true);
startInterval();
html,body{ height:100%; width:100%;overflow:hidden;}
.chatbox__body {
overflow-y: auto;
height:100%;
}
#content{
height:200%;
width:100%;
background-color:red;
}
<div class="chatbox__body" id="scrollbody">
<div id="content"></div>
</div>
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
I want to give blink effect(dark and light) when clicked on the button.I have written the following code but it does not work.So please help me.
$(document).ready(function () {
$(".search").click(function () {
setInterval(function () {
var curSrc = $("#red").attr('src');
if (curSrc === '../images/lightred.jpg') {
$(curSrc).attr("src", "../images/Darkred.jpg");
}
if (curSrc === '../images/Darkred.jpg') {
$(curSrc).attr("src", "../images/lightred.jpg");
}
}, 2000);
});
});
curSrc is your source attribute, yet you are trying to wrap it in jQuery, that won't make it an object. You'll have to target #red again and then set the source:
if (curSrc === '../images/lightred.jpg') {
$("#red").attr("src", "../images/Darkred.jpg");
}
if (curSrc === '../images/Darkred.jpg') {
$("#red").attr("src", "../images/lightred.jpg");
}
It seems the question might be how to make the button blink. This can be done with the css background-color property. CSS is a better fit, assuming lightRed and darkRed are solid colors. If the images are required you can use the background-image property.
<input type="button" class="search lightRed" value="Search"/>
<style>
.lightRed { background-color: lightcoral }
.darkRed { background-color: darkRed }
</style>
<script>
$(document).ready(function(){
$(".search").click(function(){
setInterval(function(){
var isLightRed = $(".search").hasClass("lightRed");
if (isLightRed) {
$(".search").removeClass("lightRed").addClass("darkRed");
} else {
$(".search").removeClass("darkRed").addClass("lightRed");
}
},2000);
});
});
</script>
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.
Normally, I’d set the interval to a variable and then clear it like var the_int = setInterval(); clearInterval(the_int); but for my code to work I put it in an anonymous function:
function intervalTrigger() {
setInterval(function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000);
};
intervalTrigger();
How do I clear this? I gave it a shot and tried var test = intervalTrigger(); clearInterval(test); to be sure, but that didn’t work.
Basically, I need this to stop triggering once my Google Map is clicked, e.g.
google.maps.event.addListener(map, "click", function() {
//stop timer
});
The setInterval method returns a handle that you can use to clear the interval. If you want the function to return it, you just return the result of the method call:
function intervalTrigger() {
return window.setInterval( function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000 );
};
var id = intervalTrigger();
Then to clear the interval:
window.clearInterval(id);
// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
console.log('someProcess() has been called');
// If some condition is true clear the interval
if (stopIntervalIsTrue) {
window.clearInterval(intervalListener);
}
}
the_int=window.clearInterval(the_int);
Simplest way I could think of: add a class.
Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause/unpause</button></p>