$(function(){
var x = $('.my__list').children();
for (var i = 0; i < x.length ; i += 2) {
var windowSize = $(window).width();
if(windowSize < 500) {
x.slice(i,i+1).wrapAll('<div class="'+ i +'"></div>');
}
if(windowSize > 500) {
x.slice(i,i+2).wrapAll('<div class="'+ i +'"></div>');
console.log("test");
}
}
});
I want to unwrap all my list when the browser's width change. At the moment it only change when the user refresh the browser. Thank you.
I get the source from https://codepen.io/Kibs/pen/aNzvBG
I fixed the problem by using a row function from slick and some modification inside slick.js. There is some bug from rows: 2 to rows: 1 when i used it in responsive settings.
I got the answer from here and it works for me:
Slick.prototype.buildRows = function() { ... }
Slick.prototype.cleanUpRows = function() { ... }
and change the if condition from if(.options.rows > 1) to if(.options.rows > 0)
You can hook this up to the window resize event, or in JQuery $(window).resize():
$(function(){
resizeAndWrap(); // Runs once on page load
$(window).resize(function() {
resizeAndWrap(); // Runs everytime window is resized
});
});
function resizeAndWrap() {
var x = $('.my__list').children();
for (var i = 0; i < x.length ; i += 2) {
var windowSize = $(window).width();
if(windowSize < 500) {
x.slice(i,i+1).wrapAll('<div class="'+ i +'"></div>');
}
if(windowSize > 500) {
x.slice(i,i+2).wrapAll('<div class="'+ i +'"></div>');
console.log("test");
}
}
}
Here is the codepen example with my changes
Related
I want to check the height of an element every time the site changes, because of a viewport resize or a click event.
At the moment I'm using the following code:
jQuery(function ($) {
var height = document.getElementById("head").offsetHeight;
var x = document.getElementsByClassName("dropdown-menu");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.top = height + 'px';
}
});
It's possible that the height of "head" changes. So I need to check the actual height if there are any changes at the site/viewport.
Is there a way to do so?
You can check on window resize
$( window ).resize(function() {
//check element height
});
You can use onresize event listener of javascript
var header= document.getElementById("head")
header.addEventListener('onresize', function(){
// do your code here
});
var element = document.getElementById("head"),
height;
function eventHandler () {
height = element.offsetHeight;
console.log(height);
// rest of your code
}
window.addEventListener('resize', eventHandler)
element.addEventListener('click', eventHandler)
You can bind two different event listeners and pass the same function as a callback if you want to share code logic and reduce redundancy.
My solution:
$( window ).ready(function() {
var height = document.getElementById("head").offsetHeight;
var x = document.getElementsByClassName("dropdown-menu");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.top = height + 'px';
}
});
$( window ).click(function() {
setTimeout(function() {
var height = document.getElementById("head").offsetHeight;
var x = document.getElementsByClassName("dropdown-menu");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.top = height + 'px';
}
}, 500);
});
$( window ).resize(function() {
var height = document.getElementById("head").offsetHeight;
var x = document.getElementsByClassName("dropdown-menu");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.top = height + 'px';
}
});
The timeout is for the correct height after the click and an animation.
I have 2 different functions to call based on the size of the screen. I call them in ready function like this:
$(document).ready(function() {
var $window = $(window);
var $window_width = $(window).width();
if ($window_width < 768) {
faq_mobile();
} else {
faq();
}
});
But again I want call them on window resize event since the functions are not called then. So I wrote this:
$(window).bind('resize', function(e) {
window.resizeEvt;
$(window).resize(function() {
clearTimeout(window.resizeEvt);
window.resizeEvt = setTimeout(function() {
if ($(window).width() < 768) {
faq_mobile();
} else {
faq();
}
}, 250);
});
});
But this does not work properly since the functions faq and faq_mobile have been called multiple times when I resize the window. What is the best solution for on this case?
function handler() { // separate the code and wrap it in a function
var $window_width = $(window).width();
if ($window_width < 768) {
faq_mobile();
} else {
faq();
}
}
$(handler); // on load of the document
$(window).resize(handler); // on resize of the window
If you want to keep the delay of the resize event, then change the last line above to this:
$(window).resize(function() {
window.clearTimeout(window.resizeEvt); // remove previous delay if any
window.resizeEvt = setTimeout(function() { // create a new delay
handler();
window.resizeEvt = 0;
}, 250);
});
Well.. thanks everyone for help. I googled it a bit and found a fix for it. I had to unbind the events which were added inside faq and faq_mobile functions after a resize is done. Then call those functions again. Here is the modified code: (Thanks #disstruct for your advice).
$(document).ready(function() {
var width = $(window).width();
handleView(width);
});
$(window).bind('resize', function(e) {
window.resizeEvt;
$(window).resize(function() {
clearTimeout(window.resizeEvt);
window.resizeEvt = setTimeout(function() {
// here i am unbinding the click events which were previously added inside faq and faq_mobile functions.
$('.faq-expand, .answer-close').off('click');
var width = $(window).width();
handleView(width);
}, 250);
});
});
function handleView(width) {
if (width < 768) {
faq_mobile();
} else {
faq();
}
}
Your code looks a little strange. Consider this example
var isMobileView = false;
var isDesktopView = false;
function handleView(width) {
if (width < 768 && isDesktopView) {
faq_mobile();
isMobileView = true;
isDesktopView = false;
} else if (width >= 768 && isMobileView) {
faq();
isMobileView = false;
isDesktopView = true;
}
}
$(document).ready(function() {
var width = $(window).width();
handleView(width)
});
$(window).resize(function() {
var width = $(window).width();
handleView(width)
})
I have some code that I found online that makes both divs on my website become equal lengths. However, this code only works after the page is refreshed and I have no idea what would cause this. Any help would be appreciated!
// EQUAL HEIGHTS
$.fn.equalHeights = function(px) {
$(this).each(function(){
var currentTallest = 0;
$(this).children().each(function(i){
if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
});
if (!px && Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
// for ie6, set height since min-height isn't supported
if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
$(this).children().css({'min-height': currentTallest});
});
return this;
};
// just in case you need it...
$.fn.equalWidths = function(px) {
$(this).each(function(){
var currentWidest = 0;
$(this).children().each(function(i){
if($(this).width() > currentWidest) { currentWidest = $(this).width(); }
});
if(!px && Number.prototype.pxToEm) currentWidest = currentWidest.pxToEm(); //use ems unless px is specified
// for ie6, set width since min-width isn't supported
if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'width': currentWidest}); }
$(this).children().css({'min-width': currentWidest});
});
return this;
};
// CALL EQUAL HEIGHTS
$(function(){ $('#equalize').equalHeights(); });
This behavior happens because the plugin was not well written. I've modified it for you and now it should work.
Working DEMO
Plugin script:
// EQUAL HEIGHTS
$.fn.equalHeights = function(px) {
var currentTallest = 0;
$(this).each(function(){
$(this).siblings().each(function(i){
if ($(this).height() > currentTallest) {
currentTallest = $(this).height();
}
});
});
if (!px && Number.prototype.pxToEm) {
currentTallest = currentTallest.pxToEm();
}
$(this).siblings().css({'height': currentTallest, 'min-height': currentTallest});
return this;
};
You can modify the equalWidths plugin to work as this plugin.
put all your code in jquery ready function. inside ready function code executes when the DOM is ready
$(document).ready(function(){
//your code
});
I have a single level navigation list. What I want to do is, on window resize, add a dropdown at the end to display elements that do not fit the window width.
Below an image representation:
var base = this,
container = $(base.selector),
items = container.find('>li:not(.smallmenu):visible'),
count = container.find('>li:not(.smallmenu):visible').length,
listWidth = [],
added;
items.each(function() {
listWidth.push($(this).width());
});
function getWidth() {
var width = 0;
container.find('>li:not(.smallmenu):visible').each(function() {
width += $(this).outerWidth();
});
return width + 100;
}
function hideLast() {
var i = container.find('>li:not(.smallmenu):visible').last().index()
if( $(window).width() < (getWidth()) ) {
items.eq(i).hide();
if(!added) {
$('<li class="smallmenu"><i class="fa fa-plus"></i></li>').appendTo(container);
added = true;
}
}
}
function showLast() {
var i = container.find('>li:not(.smallmenu):visible').last().index();
if( (getWidth() + listWidth[i+1]) < $(window).width() ) {
container.find('>li:not(.smallmenu)').eq(i+1).show();
if((i+2) === count) {
container.find('.smallmenu').remove();
added = false;
}
}
}
$(window).resize(function() {
showLast();
hideLast();
});
However this is not working as expected and half-done. I feel like I am heading in the wrong direction.
EDIT: Here is an updated jsFiddle: http://jsfiddle.net/anteksiler/zyv8f/1/ Resize your browser to get the effect.
I have a gallery of three Grids with images. The grid sizes changes depending on the screen size, and I have achieved that using Media-Query - ie, on desktop the grid's width will be 33% to make three columns view next to each other, and on tablet it will be 50% to make two columns view, and on phone it will be a 100% for each grid making one column view.
The reason I did this is to create a tiled gallery with images of different heights - and if I did it the normal way it will generate White-empty-spaces when floating.
So to fix this problem, and with the help of few members on this website, we have created a JavaScrip function that will MOVE all of the images that are inside Grid3 equally to Grid1 & Grid2 when screen size is tablet, so we get rid of the third grid making a view of fine two columns. Everything is working great!
Now, the problem is - on Chrome & IE - The function is being fired before its time for some reason that I need your help to help me find it! Please try it your self here: [http://90.195.175.51:93/portfolio.html][2]
Slowly on Chrome or IE - (try it on Firefox as well) - try to re-size the window from large to small, you will notice that BEFORE the top header changes to be a responsive Header (which indicate that you are on a small screen) the images have been sent to Grid1 and Grid 2! but a few px before the time. As on the function it says to fire it on <770.
Hope my question is clear enough for you to help me solve this issue which is stopping me from launching my website. Thanks.
Here is the JavaScrip:
//Gallery Grid System//
var testimonial = $(".testimonial, .galleryItem", "#grid3");
(function () {
$(document).ready(GalleryGrid);
$(window).resize(GalleryGrid);
})(jQuery);
function GalleryGrid() {
var grid3 = $('#grid3');
var width = $(window).width();
if (width < 1030 && width > 770) {
var grid1 = $('#grid1');
var grid2 = $('#grid2');
for (var i = 0; i < testimonial.length; i++) {
if (i < testimonial.length / 2) {
grid1.append(testimonial[i]);
} else {
grid2.append(testimonial[i]);
}
}
} else {
grid3.append(testimonial);
}
}
Note: The following is the whole page with all the functions:
$(document).ready(function () {
//Prevent clicking on .active links
$('.active').click(function (a) {
a.preventDefault();
});
//Allow :active on touch screens
document.addEventListener("touchstart", function () {}, true);
//Hide toolbar by default
window.addEventListener('load', function () {
setTimeout(scrollTo, 0, 0, 0);
}, false);
//Scroll-up button
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.scrollup').fadeIn();
} else {
$('.scrollup').fadeOut();
}
});
$('.scrollup').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
//StickyBox
$(function () {
$.fn.scrollBottom = function () {
return $(document).height() - this.scrollTop() - this.height();
};
var $StickyBox = $('.detailsBox');
var $window = $(window);
$window.bind("scroll resize", function () {
var gap = $window.height() - $StickyBox.height() - 10;
var footer = 288 - $window.scrollBottom();
var scrollTop = $window.scrollTop();
$StickyBox.css({
top: 'auto',
bottom: 'auto'
});
if ($window.width() <= 770) {
return;
$StickyBox.css({
top: '0',
bottom: 'auto'
});
}
if (scrollTop < 50) {
$StickyBox.css({
bottom: "auto"
});
} else if (footer > gap - 100) {
$StickyBox.css({
top: "auto",
bottom: footer + "px"
});
} else {
$StickyBox.css({
top: 80,
bottom: "auto"
});
}
});
});
//Change items location depending on the width of the screen//
$(function () { //Load Ready
function myFunction() {
var insert = $(window).width() <= 770 ? 'insertBefore' : 'insertAfter';
$('#home-sectionB img')[insert]($('#home-sectionB div'));
$('#home-sectionD img')[insert]($('#home-sectionD div'));
}
myFunction(); //For When Load
$(window).resize(myFunction); //For When Resize
});
//Contact Form//
$(".input").addClass('notSelected');
$(".input").focus(function () {
$(this).addClass('selected');
});
$(".input").focusout(function () {
$(this).removeClass('selected');
});
$(document).ready(function () {
GalleryGrid();
$(window).resize(GalleryGrid);
});
//Gallery Grid System//
var testimonial = $(".testimonial, .galleryItem", "#grid3");
(function () {
$(document).ready(GalleryGrid);
$(window).resize(GalleryGrid);
})(jQuery);
function GalleryGrid() {
var grid3 = $('#grid3');
var width = $(window).width();
if (width < 1030 && width > 770) {
var grid1 = $('#grid1');
var grid2 = $('#grid2');
for (var i = 0; i < testimonial.length; i++) {
if (i < testimonial.length / 2) {
grid1.append(testimonial[i]);
} else {
grid2.append(testimonial[i]);
}
}
} else {
grid3.append(testimonial);
}
}
//Testimonials Animation//
$(".testimonial").hover(function () {
$(".testimonial").addClass('testimonialNotActive');
$(this).removeClass('testimonialNotActive').addClass('testimonialActive');
},
function () {
$(".testimonial").removeClass('testimonialNotActive');
$(this).removeClass('testimonialActive');
});
//Portfolio Gallery Filter//
(function () {
var $portfolioGallerySection = $('#portfolio-sectionB'),
$filterbuttons = $('#portfolio-sectionA a');
$filterbuttons.on('click', function () {
var filter = $(this).data('filter');
$filterbuttons.removeClass('portfolio-sectionAClicked');
$(this).addClass('portfolio-sectionAClicked');
$portfolioGallerySection.attr('class', filter);
$('.galleryItem').removeClass('selectedFilter');
$('.galleryItem.' + filter).addClass('selectedFilter');
});
}());
});
Your problem is that CSS media queries and jQuery's $(window).width() do not always align.
function getCSSWidth() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return e[ a+'Width' ];
}
Use this instead of $(window).width()
modified from http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
I think this could solve your problem (but I'm not quite sure)
//Put that before the document ready event
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
// Here you call GalleryGrid (replace $(window).resize(GalleryGrid) with that):
$(window).smartresize(GalleryGrid);
http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
The reason is your vertical scrollbar. Your content is fixed at width=1030, but when the window size is 1030, the size of the viewport is actually: window size (1030) - vertical scroll bar
Try setting
<body style="overflow:hidden">
You will see that it works correctly when the scrollbar is removed. Or try setting:
<link href="assets/css/tablets-landscape.css" rel="stylesheet" type="text/css" media="screen and (max-width : 1045px)"/>
Set max-width:1045px to make up for scrollbar, you will see that it works correctly.
Your javascript should be like this:
var width = $(window).width() + verticalscrollbarWidth;