Saving CSS class on object in localstorage on reload page - javascript

What I would like to do, is to have a CSS style saved when a user resreshes the page. This is my jQuery code:
$(function() {
$("#slider").draggable({
axis: 'x',
containment: 'parent',
drag: function(event, ui) {
if (ui.position.left > 230) {
$("#well").fadeOut();
$( "#well" ).addClass( "disappear" );
} else {
// Apparently Safari isn't allowing partial opacity on text with background clip? Not sure.
// $("h2 span").css("opacity", 100 - (ui.position.left / 5))
}
},
stop: function(event, ui) {
if (ui.position.left < 231) {
$(this).animate({
left: 0
})
}
}
});
$('#slider')[0].addEventListener('touchmove', function(event) {
event.preventDefault();
var el = event.target;
var touch = event.touches[0];
curX = touch.pageX - this.offsetLeft - 73;
if(curX <= 0) return;
if(curX > 230){
$('#well').fadeOut();
}
el.style.webkitTransform = 'translateX(' + curX + 'px)';
}, false);
$('#slider')[0].addEventListener('touchend', function(event) {
this.style.webkitTransition = '-webkit-transform 0.3s ease-in';
this.addEventListener( 'webkitTransitionEnd', function( event ) { this.style.webkitTransition = 'none'; }, false );
this.style.webkitTransform = 'translateX(0px)';
}, false);
});
When the class "disappear" is added I would like to keep it added even if the page reloads. I found a useful post here, but since I am a beginner at Javascript, I am not sure how to use it in my case, and I would be really happy if someone could give me a personalized answer.
Thanks in advance!

After $( "#well" ).addClass( "disappear" ); add
localStorage['wellClass'] = 'disappear';
And in the line below $(function() { add
previousWellClass = localStorage['wellClass'];
if (previousWellClass) $('#well').addClass(previousWellClass);

This will do most of the work for you.
var setClass = JSON.parse(localStorage.getItem('setClass')) || {};
$.each(setClass, function () {
$(this.selector).addClass(this.className);
});
var addClassToLocalStorage = function(selector, className) {
setClass[selector + ':' + className] = {
selector: selector,
className: className
};
localStorage.setItem('setClass', JSON.stringify(setClass));
};
var removeClassFromLocalStorage = function(selector, className) {
delete setClass[selector + ':' + className];
localStorage.setItem('setClass', JSON.stringify(setClass));
};
Then you can just do this:
$("#well").fadeOut();
$("#well").addClass("disappear");
addClassToLocalStorage('#well', 'disappear');
// remove it removeClassFromLocalStorage('#well', 'disappear');
FIDDLE
Then you can reuse it if you need to later.

Related

jQuery function as parameter of other jQuery function does not work

I have been reading several similar questions about this, but I can't get it to work. I have a scroll detection function in jQuery, which I want to have 3 parameters:
function scroll_detection(box_selector, trigger_offset, the_animation){
//something here
the_animation();
}
Where the_animation is a function that will be called like this:
scroll_detection("section", .8, function(){
//stuff here
});
The problem is, when I add the function, the animation do not run anymore.
This code works perfectly:
function scroll_detection(duration, box_selector, element_selector, ease, trigger_offset ){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top - ($(window).scrollTop() + effect_offset);
if (position <= 0) {
$(this).find(element_selector).animate( { marginLeft: "0" }, duration, ease );
}
});
});
}
scroll_detection(2000, "section", ".section-title", "easeOutBack", .8);
scroll_detection(3000, ".article-wrap", ".article-title", "easeOutBounce", .7);
But this does not:
function scroll_detection(the_animation, box_selector, trigger_offset ){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top - ($(window).scrollTop() + effect_offset);
if (position <= 0) {
the_animation();
}
});
});
}
scroll_detection( function(){
$(this).find(".section-title").animate( { marginLeft: "0" }, 2000, "easeOutBounce");
}, "section", .8);
I want to be able to change easily what kind of effect I want. Any help will be appreciated.
Edit 11/09/2015:
As #Aguardientico and #LuiGui pointed out, the problem was the scope of the $(this) inside the callback function, and I went with the #Aguardientico solution.
jQuery(document).ready(function($){
function scroll_detection(the_animation, box_selector, trigger_offset ){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top - ($(window).scrollTop() + effect_offset);
if (position <= 0) {
the_animation.call(post); //Add call to give the function the right scope
}
});
});
}
scroll_detection( function(){
$(this).find(".section-title").animate( { marginLeft: "0" }, 2000, "easeOutBounce");
}, "section", .8);
It looks like an issue related with scope, you are calling $(this) inside your anonymous function aka the_animation, what if you do the following? the_animation.call(post)
function scroll_detection(the_animation, box_selector, trigger_offset ){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top - ($(window).scrollTop() + effect_offset);
if (position <= 0) {
the_animation.call(post);
}
});
});
}
scroll_detection( function(){
$(this).find(".section-title").animate( { marginLeft: "0" }, 2000, "easeOutBounce");
}, "section", .8);
You are function calls DO NOT match the function definitions.
Your parameters are OUT OF ORDER.
Try this NEW CODE:
var scroll_detection = function scroll_detection_func(
the_animation, box_selector, trigger_offset
){
var effect_offset = Math.floor($(window).height() * trigger_offset);
$(window).bind('scroll', function() {
$(box_selector).each(function() {
var post = $(this);
var position = post.position().top
- ($(window).scrollTop()
+ effect_offset)
;
if (position <= 0) {
the_animation();
}
});
});
}
scroll_detection(
function(){
$(this).find(".section-title").animate({
marginLeft: "0" },
2000, "easeOutBounce"
);
}, //the_animation
"section", //box_selector
.8 //trigger_offset
);
From the code you give,the_animation means
$(this).find(element_selector).animate( { marginLeft: "0" }, duration, ease );
so you can there is a this in your function. When you pass a function with this as a parameter, you need to specify what this mean, just try to specify the scope of this use apply(),bind() or 'call()' function, here are some explanations:
http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/

JavaScript function is preventing link working

This javascript function is used to animate a number of selection boxes, however, I want to be able to use these selection boxes as A HREF links but i believe that something in this javascript is preventing it from acting as a href link.
Please could someone help point me in the right direction
Any help much appreciated thank you
(function() {
var $container = $('#portfolio-items');
if( $container.length ) {
var $itemsFilter = $('#portfolio-items-filter'),
mouseOver;
// Copy categories to item classes
$('article', $container).each(function(i) {
var $this = $(this);
$this.addClass( $this.attr('data-categories') );
});
// Run Isotope when all images are fully loaded
$(window).on('load', function() {
$container.isotope({
itemSelector : 'article',
layoutMode : 'fitRows'
});
});
// Filter projects
$itemsFilter.on('click', 'a', function(e) {
var $this = $(this),
currentOption = $this.attr('data-categories');
$itemsFilter.find('a').removeClass('active');
$this.addClass('active');
if( currentOption ) {
if( currentOption !== '*' ) currentOption = currentOption.replace(currentOption, '.' + currentOption)
$container.isotope({ filter : currentOption });
}
e.preventDefault();
});
$itemsFilter.find('a').first().addClass('active');
$itemsFilter.find('a').not('.active').hide();
// On mouseover (hover)
$itemsFilter.on('mouseenter', function() {
var $this = $(this);
clearTimeout( mouseOver );
// Wait 100ms before animating to prevent unnecessary flickering
mouseOver = setTimeout( function() {
if( $(window).width() >= 960 )
$this.find('li a').stop(true, true).slideHorzShow(300);
}, 100);
}).on('mouseleave', function() {
clearTimeout( mouseOver );
if( $(window).width() >= 960 )
$(this).find('li a').not('.active').stop(true, true).slideHorzHide(150);
});
}
})();
Just remove:
e.preventDefault();

Something is wrong with this 3-panes splitter

I'm trying to resize 3 panes inside a container , when resized, they shouldn't exceed the width of container (do not get out of it)..
But in this snippet http://jsfiddle.net/KXsrd/ , when I resize the second one, it successfully decreases the next element or increases depending on the direction. but sometimes it causes the next sibling to drop below the container and although the next sibling decreases its size when I expand one , it keeps 'shaking' ..
Here is the main function:
$(function () {
$('.col').each(function (e, u) {
$(u).data({ow: $(u).width()});
})
$(".col").resizable(
{
handles: 'e',
start: function (e) {
},
resize: function (e, ui) {
var el = ui.element;
var parent = el.parent();
var next = el.next();
var siblings = el.siblings();
var siblingsWidth = (function () {
var totalWidth = 0;
_.each(siblings, function (el) {
totalWidth += $(el).width();
});
return totalWidth;
})();
var currentSize = ui.size;
if (currentSize.width > $(el).data('ow')) {
next.css({width: '-=' + (currentSize.width - $(el).data('ow'))});
} else {
next.css({width: '+=' + ( $(el).data('ow') - currentSize.width )});
}
if (currentSize.width + siblingsWidth >= $(parent).width()) {
$(el).width($(parent).width() - siblingsWidth)
}
$(el).data({ow: currentSize.width});
},
stop: function (e, ui) {
}
});
});
Any help would be much appreciated ..
(PS. I tried many plugins for resizable panes. but they all work on 2 panes only)

Combining draggable, droppable, sortable, tabs, clone accordion

I have been trying to combine all the Interactions and Widgets mentioned above and som effects and i was able to do some of them successfully, as you can see in my "fiddle".
But some of them like cloning the element when it's dragged to another tab, or making the accordion only work when it's pressed a (minus icon in the panel title), or deffining only one tab to be droppable but not draggable.
Using Connect lists with Tabs i was able to define a base to work.
I can remove the item (Sep1) with this code:
jQuery(document).ready(function () {
$(".glyphicon-remove").bind('click', $.proxy(function (event) {
var status = $(event.target).attr('id').split("_");
$("#chart_" + status[1] + "_" + status[2]).hide("drop", {
direction: "up"
}, "slow");
}, this));
});
and partially do the accordion
jQuery(document).ready(function () {
$(".glyphicon-minus").bind('click', $.proxy(function (event) {
var status = $(event.target).attr('id').split("_");
$("#accordion_" + status[1] + "_" + status[2]).accordion({
collapsible: true
});
}, this));
});
the accordion problem is that after a click the button the first time it will apply the widget to all panel header and i only want it to apply it to a button.
Can anyone explain me how can i do it and if possible provide me some code with examples?
I was able to create a solution.
Here it is
$(function () {
$(".connectedSortable").sortable(
{
tolerance: 'pointer',
cursor: 'move',
forcePlaceholderSize: true,
dropOnEmpty: true,
connectWith: 'ul.connectedSortable',
placeholder: "ui-state-highlight"
}
).disableSelection();
var $tabs = $("#tabs").tabs();
var $tab_items = $("ul:first li", $tabs).droppable({
accept: ".connectedSortable li",
hoverClass: "ui-state-hover",
tolerance: 'pointer',
drop: function (event, ui) {
var source = $(ui.draggable[0]).parent().attr("id").split("-")[1];
var target = $(event.target).children("a").attr("href").split("-")[1];
if (source == target) {
return false;
}
var $item = $(this);
var $list = $($item.find("a").attr("href")).children();
var $dragged = ui.draggable.clone().removeAttr('style');
//var id = Check($dragged);
//if (id != false) {
var $chartId = "chart_0_" + id;
var $accordionId = "accordion_0_" + id;
var $minimizeId = "minimize_0_" + id;
var $closeId = "close_0_" + id;
$dragged.find("div[id^='chart']").attr("id", $chartId);
$dragged.find("div[id^='accordion']").attr("id", $accordionId);
$dragged.find("i[id^='minimize']").attr("id", $minimizeId);
$dragged.find("i[id^='close']").attr("id", $closeId);
if ((source == 1 || source == 2) && target === 0) {
$tabs.tabs("option", "active", $tab_items.index($item));
$dragged.appendTo($list);
}
//}
}
});
$(".glyphicon-minus").click(function (event) { //ocultar grafico (panel body)
var status = $(event.target).attr('id').split("_");
$("#accordion_" + status[1] + "_" + status[2]).slideToggle("slow");
});
$(".glyphicon-remove").click(function (event) { // eliminar separador
var status = $(event.target).attr('id').split("_");
$("#chart_" + status[1] + "_" + status[2]).hide("drop", {
direction: "up"
}, "slow");
});
$(".glyphicon-floppy-save").click(function (event) { // guardar ordem de elementos dos separadores
var $saveSortIds = [];
for (var i = 0; i < 3 ; i++)
$saveSortIds[i] = $("#sortable-" + i).sortable("toArray"); //1 para cada separador
});
});

Animation ( bar fills up over time ) with Jquery (Suggestion)

I would like to replicate the same functionality as at ign.com, where the indicator bar fills up over time. I got it working but I got some sync issues after a while. So i'm open to suggestions to do it from scratch (I'm beginner with all this animation stuff).
This is the code.
function GoProgressBar() {
var $lineStatus = $('.featured-articles-line-status');
$lineStatus.css('width', '0px');
$lineStatus.animate({ width: '694px' }, 12000, 'linear', GoProgressBar);
};
function GoOverlay(width, isLast, currentWidth) {
var $overlayLine = $('.status-overlay');
if (isLast) {
$overlayLine.css('width', '0px');
return;
}
if (currentWidth) {
$overlayLine.css('width', currentWidth);
$overlayLine.animate({ width: width }, 700);
} else {
$overlayLine.css('width', '0px');
$overlayLine.animate({ width: width }, 700);
}
};
function ShowNextElement() {
var $elements = $('.element'),
$overlayLine = $('.status-overlay'),
$liElements = $('#elements li'),
width;
if (currentElement === elements[elements.length - 1]) {
currentWidth = $overlayLine.width() + 'px',
width = currentWidth + $($liElements[(elements.length - 1)]).outerWidth() + 'px';
GoOverlay(width, true, currentWidth);
currentElement = elements[0];
$elements.hide();
$(currentElement).fadeIn(1000);
return;
}
i = elements.indexOf(currentElement) + 1;
var currentTab = $liElements[(i - 1)],
currentWidth = $overlayLine.width();
if (currentWidth) {
width = currentWidth + $(currentTab).outerWidth() + 'px';
GoOverlay(width, false, currentWidth);
} else {
width = $(currentTab).outerWidth() + 'px';
GoOverlay(width, false, false);
}
currentElement = elements[i];
$elements.hide();
$(currentElement).fadeIn(1000);
}
Thanks!
http://jqueryui.com/progressbar/
You could try this..
There are more features in addition to this,check it out.
Might come useful :)
There are a wealth of ways in which you could do this.
You should have some kind of controller to manage the show and hide.
var Application = {
show : function() {
jQuery('.application-overlay').stop().animate({ top: 40 }, 500);
jQuery('.cf-ribbon').stop().animate({height: 1000},500);
},
hide : function() {
jQuery('.application-overlay').stop().animate({ top: -1200 }, 500);
jQuery('.cf-ribbon').stop().animate({height: 200},500);
}
};
Then you have your triggers : Application.show();
jQuery(document).ready(function() {
jQuery('.cf-speakers .span2 a').hover(function() {
jQuery('span',this).stop().animate({ opacity: 1.0 },100);
}, function() {
jQuery('span',this).stop().animate({ opacity: 0.0 },100);
});;
jQuery('.apply-now').click(function(e) {
Application.show();
e.stopPropagation();
e.preventDefault();
});
jQuery('body').click(function(e) {
var application = jQuery('.application-overlay');
if( application.has(e.target).length === 0)
Application.hide();
});
jQuery('.gallery a').click(function(e) {
var src = jQuery(this).attr('href');
jQuery('.main-container img').hide().attr('src', src).fadeIn('fast');
jQuery('.gallery a').each(function() {
jQuery(this).removeClass('active');
});
jQuery(this).addClass('active');
e.stopPropagation();
e.preventDefault();
});
});
Your css would of course come into play also but that can be left to you!
This should give you an example of what you need .. But you're already on the right track, sometimes there is merit in reusing other people code too you know! :)

Categories

Resources