Rename a function after resizing screen - javascript

is possible to change a name of a function after resizing screen?
I have this
<div id="box1" data-same-height="blocks-resize">
where
data-same-height="blocks-resize"
is the function, and here's the javascript of that function.
$(document).ready(function() {
var equalize = function () {
var disableOnMaxWidth = 0; // 767 for bootstrap
var grouped = {};
var elements = $('*[data-same-height]');
elements.each(function () {
var el = $(this);
var id = el.attr('data-same-height');
if (!grouped[id]) {
grouped[id] = [];
}
grouped[id].push(el);
});
$.each(grouped, function (key) {
var elements = $('*[data-same-height="' + key + '"]');
elements.css('height', '');
var winWidth = $(window).width();
if (winWidth <= disableOnMaxWidth) {
return;
}
var maxHeight = 0;
elements.each(function () {
var eleq = $(this);
maxHeight = Math.max(eleq.height(), maxHeight);
});
elements.css('height', maxHeight + "px");
});
};
var timeout = null;
$(window).resize(function () {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(equalize, 250);
});
equalize();
});
It's possible to change that name (data-same-height) after resizing screen to 600px? or could be also the "blocks-resize" too
Thanks!

$(function(){
$(window).on("resize load", responsive);
})
var responsive = function() {
if(window.innerWidth < 600) {
//do your thing
} else {
//do something else.
}
}

Related

Universal script for moving elements in DOM

I want to create a universal code for easy moving elements in DOM between desktop and mobile. It's not my idea as well as not my code. It was for Prestashop 1.7 only, but I want to change it for any project.
The idea is that you can wrap some code you want to move in an absolute different place on mobile with <div id="_desktop_some-block">Some content</div>, and place empty <div id="_mobile_some-block"></div> where you want to see it on mobile devices and when window reach (for ex.) 768px the HTML of the element will be moving to another one.
So here is an original code:
import $ from 'jquery';
import prestashop from 'prestashop';
prestashop.responsive = prestashop.responsive || {};
prestashop.responsive.current_width = window.innerWidth;
prestashop.responsive.min_width = 768;
prestashop.responsive.mobile = prestashop.responsive.current_width < prestashop.responsive.min_width;
function swapChildren(obj1, obj2)
{
var temp = obj2.children().detach();
obj2.empty().append(obj1.children().detach());
obj1.append(temp);
}
function toggleMobileStyles()
{
if (prestashop.responsive.mobile) {
$("*[id^='_desktop_']").each(function(idx, el) {
var target = $('#' + el.id.replace('_desktop_', '_mobile_'));
if (target.length) {
swapChildren($(el), target);
}
});
} else {
$("*[id^='_mobile_']").each(function(idx, el) {
var target = $('#' + el.id.replace('_mobile_', '_desktop_'));
if (target.length) {
swapChildren($(el), target);
}
});
}
prestashop.emit('responsive update', {
mobile: prestashop.responsive.mobile
});
}
$(window).on('resize', function() {
var _cw = prestashop.responsive.current_width;
var _mw = prestashop.responsive.min_width;
var _w = window.innerWidth;
var _toggle = (_cw >= _mw && _w < _mw) || (_cw < _mw && _w >= _mw);
prestashop.responsive.current_width = _w;
prestashop.responsive.mobile = prestashop.responsive.current_width < prestashop.responsive.min_width;
if (_toggle) {
toggleMobileStyles();
}
});
$(document).ready(function() {
if (prestashop.responsive.mobile) {
toggleMobileStyles();
}
});
Here is what I'm trying to do:
var windowWidth = $(window).innerWidth();
var windowMinWidth = 768;
var windowResponsiveMobile = windowWidth < windowMinWidth;
function swapChildren(obj1, obj2)
{
var temp = obj2.children().detach();
obj2.empty().append(obj1.children().detach());
obj1.append(temp);
}
function toggleMobileStyles()
{
if (windowResponsiveMobile) {
$("*[id^='_desktop_']").each(function(idx, el) {
var target = $('#' + el.replace('_desktop_', '_mobile_'));
if (target.length) {
swapChildren($(el), target);
}
});
} else {
$("*[id^='_mobile_']").each(function(idx, el) {
var target = $('#' + el.replace('_mobile_', '_desktop_'));
if (target.length) {
swapChildren($(el), target);
}
});
}
}
$(window).on('resize', function() {
var _cw = windowWidth;
var _mw = windowMinWidth;
var _w = $(window).innerWidth();
var _toggle = (_cw >= _mw && _w < _mw) || (_cw < _mw && _w >= _mw);
windowWidth = _w;
windowResponsiveMobile = windowWidth < windowMinWidth;
if (_toggle) {
toggleMobileStyles();
}
});
$(document).ready(function() {
if (windowResponsiveMobile) {
toggleMobileStyles();
}
});
Currently it doesn't work, but I don't see any errors in the console and it little bit confuse...
Please help me to finish it so it could work.
var windowWidth = $(window).innerWidth();
var windowMinWidth = 768;
var windowResponsiveMobile = windowWidth < windowMinWidth;
function swapChildren(obj1, obj2)
{
var temp = obj2.children().detach();
obj2.empty().append(obj1.children().detach());
obj1.append(temp);
}
function toggleMobileStyles()
{
if (windowResponsiveMobile) {
$("[id^='_desktop_']").each(function(idx, el) {
var target = $('#' + el.id.replace('_desktop_', '_mobile_'));
if (target.length) {
swapChildren($(el), target);
}
});
} else {
$("[id^='_mobile_']").each(function(idx, el) {
var target = $('#' + el.id.replace('_mobile_', '_desktop_'));
if (target.length) {
swapChildren($(el), target);
}
});
}
}
$(window).on('resize', function() {
var _cw = windowWidth;
var _mw = windowMinWidth;
var _w = $(window).innerWidth();
var _toggle = (_cw >= _mw && _w < _mw) || (_cw < _mw && _w >= _mw);
windowWidth = _w;
windowResponsiveMobile = windowWidth < windowMinWidth;
if (_toggle) {
toggleMobileStyles();
}
});
$(document).ready(function() {
if (windowResponsiveMobile) {
toggleMobileStyles();
}
});
Here is the updated code, you just removed the id in the target selector.

Changing windows width with JQuery without reloading the page again

I have a JQuery rotator in my website with a slides images and I want to make the website responsive. I'm using CSS media queries to do it. I want to change the slide width (which defines in JS) when the windows width is less than 800px.
So long, I did something like this:
var responsiveSlideWidth;
if ($(window).width() < 800) {
responsiveSlideWidth = 700;
}
else {
responsiveSlideWidth = 960;
}
var defaults = {
container: '.rotatorWrapper',
animationduration: 1000,
slideWidth: responsiveSlideWidth
};
The problem is that it is working just after page reload. Thats means: if I resize the window size its is not working until I reload the page.
Any suggestions?
Thanks.
EDIT: My full code:
(function ($) {
$.fn.Rotator = function (options) {
var responsiveSlideWidth;
if ($(window).width() < 800) {
responsiveSlideWidth = 700;
}
else {
responsiveSlideWidth = 960;
}
var defaults = {
container: '.rotatorWrapper',
animationduration: 1000,
slideWidth: responsiveSlideWidth
};
options = $.extend(defaults, options);
elm = this;
var pageIndex = 0,
slideCount = 0;
var _init = function () {
slideCount = elm.find(options.container).children().children().length;
elm.find(options.container).children().width(slideCount * options.slideWidth);
_bindEvents();
_togglePager();
};
var _bindEvents = function () {
var jElm = $(elm);
jElm.find('.prev').on('click', _previous);
jElm.find('.next').on('click', _next);
};
var _next = function (e) {
e.preventDefault();
if (pageIndex >= 0 && pageIndex < slideCount - 1) {
pageIndex++;
elm.find(options.container).children().animate({
left: "-=" + options.slideWidth
}, options.animationduration);
}
_togglePager();
};
var _previous = function (e) {
e.preventDefault();
if (pageIndex <= slideCount) {
pageIndex--;
elm.find(options.container).children().animate({
left: "+=" + options.slideWidth
}, options.animationduration);
}
_togglePager();
};
var _togglePager = function () {
var $elm = $(elm);
var prev = $elm.find('.prev');
var next = $elm.find('.next');
console.log('slide count' + pageIndex + ' Page Index' + pageIndex)
if (pageIndex >= slideCount - 1) {
next.hide();
} else {
next.show();
}
if (pageIndex <= 0) {
prev.hide();
} else {
prev.show();
}
}
return _init(elm);
}
})(jQuery);

Call function at scroll once

I have jQuery function counter and I need to call it when I scroll page
$(document).ready(function () {
$.fn.counter = function () {
$(this).each(function () {
var num = $(this).data('counter');
var i = 1,
self = $(this).html(i);
var interval = setInterval(function () {
self.html(++i);
if (i >= num) {
clearInterval(interval);
}
}, 100);
});
};
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > 300) {
$('.counter-1, .counter-2, .counter-3, .counter-4').counter();
}
});
});
The problem is when I scroll page again up or down function is called again and again every time.
I tried to use this code
$(document).ready(function () {
$.fn.counter = function () {
$(this).each(function () {
var num = $(this).data('counter');
var i = 1,
self = $(this).html(i);
var interval = setInterval(function () {
self.html(++i);
if (i >= num) {
clearInterval(interval);
}
}, 100);
});
};
$(window).one('scroll', function () {
var height = $(window).scrollTop();
if (height > 300) {
$('.counter-1, .counter-2, .counter-3, .counter-4').counter();
}
});
});
but in this case after the reloading the page function is not called.
Is there any way to call function only once on scroll and don't call it again but call it after the reloading the page ?
You should use a name space with .on/.off :
$(window).on('scroll.custom', function () {
var height = $(window).scrollTop();
if (height > 300) {
$('.counter-1, .counter-2, .counter-3, .counter-4').counter();
$(window).off('scroll.custom')
}
});

SinglePage navigation

My website uses onePageNav and scrollTo jquery code. I would like to insert code which correct my position on the website when i click on the same link in the navigation (i scroll mouse up or down but current button (hover) in navigation has not moved yet on to the next one).
OnePageNav code:
;
(function ($, window, document, undefined) {
// our plugin constructor
var OnePageNav = function (elem, options) {
this.elem = elem;
this.$elem = $(elem);
this.options = options;
this.metadata = this.$elem.data('plugin-options');
this.$nav = this.$elem.find('a');
this.$win = $(window);
this.sections = {};
this.didScroll = false;
this.$doc = $(document);
this.docHeight = this.$doc.height();
};
// the plugin prototype
OnePageNav.prototype = {
defaults: {
currentClass: 'current',
changeHash: true,
easing: 'swing',
filter: '',
scrollSpeed: 750,
scrollOffset: 0,
scrollThreshold: 0.5,
begin: false,
end: false,
scrollChange: false
},
init: function () {
var self = this;
// Introduce defaults that can be extended either
// globally or using an object literal.
self.config = $.extend({}, self.defaults, self.options, self.metadata);
//Filter any links out of the nav
if (self.config.filter !== '') {
self.$nav = self.$nav.filter(self.config.filter);
}
//Handle clicks on the nav
self.$nav.on('click.onePageNav', $.proxy(self.handleClick, self));
//Get the section positions
self.getPositions();
//Handle scroll changes
self.bindInterval();
//Update the positions on resize too
self.$win.on('resize.onePageNav', $.proxy(self.getPositions, self));
return this;
},
adjustNav: function (self, $parent) {
self.$elem.find('.' + self.config.currentClass).removeClass(self.config.currentClass);
$parent.addClass(self.config.currentClass);
},
bindInterval: function () {
var self = this;
var docHeight;
self.$win.on('scroll.onePageNav', function () {
self.didScroll = true;
});
self.t = setInterval(function () {
docHeight = self.$doc.height();
//If it was scrolled
if (self.didScroll) {
self.didScroll = false;
self.scrollChange();
}
//If the document height changes
if (docHeight !== self.docHeight) {
self.docHeight = docHeight;
self.getPositions();
}
}, 250);
},
getHash: function ($link) {
return $link.attr('href').split('#')[1];
},
getPositions: function () {
var self = this;
var linkHref;
var topPos;
var $target;
self.$nav.each(function () {
linkHref = self.getHash($(this));
$target = $('#' + linkHref);
if ($target.length) {
topPos = $target.offset().top;
self.sections[linkHref] = Math.round(topPos) - self.config.scrollOffset;
}
});
},
getSection: function (windowPos) {
var returnValue = null;
var windowHeight = Math.round(this.$win.height() * this.config.scrollThreshold);
for (var section in this.sections) {
if ((this.sections[section] - windowHeight) < windowPos) {
returnValue = section;
}
}
return returnValue;
},
handleClick: function (e) {
var self = this;
var $link = $(e.currentTarget);
var $parent = $link.parent();
var newLoc = '#' + self.getHash($link);
if (!$parent.hasClass(self.config.currentClass)) {
//Start callback
if (self.config.begin) {
self.config.begin();
}
//Change the highlighted nav item
self.adjustNav(self, $parent);
//Removing the auto-adjust on scroll
self.unbindInterval();
//Scroll to the correct position
$.scrollTo(newLoc, self.config.scrollSpeed, {
axis: 'y',
easing: self.config.easing,
offset: {
top: -self.config.scrollOffset
},
onAfter: function () {
//Do we need to change the hash?
if (self.config.changeHash) {
window.location.hash = newLoc;
}
//Add the auto-adjust on scroll back in
self.bindInterval();
//End callback
if (self.config.end) {
self.config.end();
}
}
});
}
e.preventDefault();
},
scrollChange: function () {
var windowTop = this.$win.scrollTop();
var position = this.getSection(windowTop);
var $parent;
//If the position is set
if (position !== null) {
$parent = this.$elem.find('a[href$="#' + position + '"]').parent();
//If it's not already the current section
if (!$parent.hasClass(this.config.currentClass)) {
//Change the highlighted nav item
this.adjustNav(this, $parent);
//If there is a scrollChange callback
if (this.config.scrollChange) {
this.config.scrollChange($parent);
}
}
}
},
unbindInterval: function () {
clearInterval(this.t);
this.$win.unbind('scroll.onePageNav');
}
};
OnePageNav.defaults = OnePageNav.prototype.defaults;
$.fn.onePageNav = function (options) {
return this.each(function () {
new OnePageNav(this, options).init();
});
};
})(jQuery, window, document);
$(function () { // this is the shorthand for document.ready
$(window).scroll(function () { // this is the scroll event for the document
scrolltop = $(window).scrollTop(); // by this we get the value of the scrolltop ie how much scroll has been don by user
if (parseInt(scrolltop) >= 80) // check if the scroll value is equal to the top of navigation
{
$("#navbar").css({
"position": "fixed",
"top": "0"
}); // is yes then make the position fixed to top 0
} else {
$("#navbar").css({
"position": "absolute",
"top": "80px"
}); // if no then make the position to absolute and set it to 80
}
}); //here
}); //here

Converting jquery to javascript progress bar

Please help me convert this JQuery to Javascript progress bar script
var generateButton = document.getElementById("generate");
if (generateButton.addEventListener) {
generateButton.addEventListener("click", random, false);
}
else if (generateButton.attachEvent) {
generateButton.attachEvent('onclick', random);
}
function random(e) {
setTimeout(function(){
$('.progress .bar').each(function() {
var me = $(this);
var perc = me.attr("data-percentage");
//TODO: left and right text handling
var current_perc = 0;
var progress = setInterval(function() {
if (current_perc>=perc) {
clearInterval(progress);
} else {
current_perc +=1;
me.css('width', (current_perc)+'%');
}
me.text((current_perc)+'%');
}, 50);
});
},300);
var num = Math.random();
var greetingString = num;
document.getElementById("rslt").innerText = greetingString;
}
Here is the Live version: http://jsfiddle.net/chjjK/9/
Pretty easy actually, use document.getElementsByClassName and a for loop to replace the each:
var bar = document.getElementsByClassName("bar");
for (var i = 0; i < bar.length; i++) {
var me = bar[i];
var perc = me.getAttribute("data-percentage");
var current_perc = 0;
var progress = setInterval(function() {
if (current_perc>=perc) {
clearInterval(progress);
} else {
current_perc +=1;
me.style.width = current_perc+'%';
}
me.innerHTML = ((current_perc)+'%');
}, 50);
}
}, 300);
Demo: http://jsfiddle.net/chjjK/13/

Categories

Resources