Unable to call a jQuery function from within .resize() - javascript

Here is my code:
function centerAlign(image, parent) {
image.load(function() {
var imageWidth = image.width();
var parentWidth = parent.width();
if(imageWidth != 0) {
var trim = (parentWidth - imageWidth) / 2;
image.css("marginLeft", trim);
}
});
}
$(window).resize(function() {
centerAlign($(".swiper-slide img"), $(".swiper-slide"));
});
$(document).ready(function() {
centerAlign($(".swiper-slide img"), $(".swiper-slide"));
});
It runs the function on page load however not on window resize. Any thoughts?

Found the solution, I was calling load within resize. Guessing as it's already loaded it wont run on resize. Changed to:
function centerAlign(image, parent) {
var imageWidth = image.width();
var parentWidth = parent.width();
if(imageWidth != 0) {
var trim = (parentWidth - imageWidth) / 2;
image.css("marginLeft", trim);
}
}
$(window).resize(function() {
centerAlign($(".swiper-slide img"), $(".swiper-slide"));
});
$(document).ready(function() {
$(".swiper-slide img").load(function() {
centerAlign($(".swiper-slide img"), $(".swiper-slide"));
});
});
Now I'm only calling load within ready() and not within resize(). Hope this helps anyone else.

Related

How to add many divs in JavaScript code

I've been designing a web infographic with some animations within the page. So I added some JavaScript code in order to trigger the animations as the user reaches them on screen.
My question is how to add many div names in a JavaScript sentence?
The name of the div is "box_info_a", I just need to add some more, but have no idea how.
This is the code:
$(function()
var $window = $(window),
win_height_padded = $window.height() * 1.1,
isTouch = Modernizr.touch;
if (isTouch) {
$('.revealOnScroll').addClass('box_info_a');
}
$window.on('scroll', revealOnScroll);
function revealOnScroll() {
var scrolled = $window.scrollTop(),
win_height_padded = $window.height() * 1.1;
// Showed...
$(".revealOnScroll:not(.box_info_a)").each(function () {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded > offsetTop) {
if ($this.data('timeout')) {
window.setTimeout(function() {
$this.addClass('box_info_a ' + $this.data('animation'));
}, parseInt($this.data('timeout'), 10));
} else {
$this.addClass('box_info_a ' + $this.data('animation'));
}
}
}); // Close Showed...
// Hidden...
$(".revealOnScroll.box_info_a").each(function (index) {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded < offsetTop) {
$(this).removeClass('box_info_a lightSpeedIn')
}
});
}
revealOnScroll();
});
Just do this:
$(document).ready(function () {
$('#trigger').click(function () {
$('#target').addClass("oneClassToAdd anotherClassToAdd");
});
});
All you have to do is put two classes in the parentheses.

Call same function in window ready and window resize

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)
})

jQuery: addClass only once

I have an addClass and removeClass function running on window resize, using an if else statement. The markup is as follows:
$(window).load(function() {
resize();
});
//Every resize of window
$(window).resize(function() {
resize();
});
//Dynamically assign height
function resize() {
// Handler for .ready() called.
var windowWidth = $(window).width(),
windowHeight = $(window).height(),
windowHeight = windowWidth / 1.7777;
var loadwindowHeight = $(window).height(),
loadspriteHeight = $('.spritespin-canvas').height();
if(loadspriteHeight < loadwindowHeight) {
$('.spritespin-canvas').addClass('height');
} else {
$('.spritespin-canvas').removeClass('height');
}
}
The only problem is, when you resize the window, it keeps repeatedly adding and removing the class, it it possible to run the addClass and removeClass functions once? Any suggestions would be greatly appreciated!
You can use .hasClass.
var hasHeightClass = $('.spritespin-canvas').hasClass('height');
if (loadspriteHeight < loadwindowHeight && !hasHeightClass) {
$('.spritespin-canvas').addClass('height');
} else if (hasClass) {
$('.spritespin-canvas').removeClass('height');
}

Jquery typing effect on scroll bug

Hi I have some js code that do typing effect on my web page it start typing when you scroll down end of page. For first it work normally but when you start scroll faster down to up the typing effect goes crazy how can I fix that
demo page
code
$(window).scroll(function (e) {
var elem = $(".hello-page");
var scrollTop = $(window).scrollTop();
var blockTop = elem.offset().top;
var docHeight = $(document).height();
var windowH = $(window).height();
if (scrollTop >= blockTop) {
var helloPageA = $(".hello-page").find("a");
var text = helloPageA.attr("data-text");
helloPageA.text('');
$.each(text.split(''), function (i, letter) {
setTimeout(function () {
helloPageA.html(helloPageA.html() + letter);
}, 150 * i);
});
} else {
elem.find("a").text('');
}
});
jsfiddle example
Thanks for your help
So, here is the solution - http://jsfiddle.net/u3ojjx8r/1/
I borrowed initial structure of the code from previous answer here and it was removed unfortunately, therefore I can't mention one of the co-authors. Though the code looked quite similar to topic-starter's one.
The idea of the code below is to separate the queuing of characters to render and the actual rendering. Another important improvement is always have control over timeouts, i.e. never schedule more than one timeout. That allows you to cancel them any time without unpredicted/uncontrolled behavior.
var timeoutVar;
var queue = [];
var drawQueueTimeout = -1;
var helloPageA = $(".hello-page").find("a");
function pushQueue (element) {
console.log('pushQUeue', element.char);
queue.push(element);
checkQueue();
}
function flushQueue () {
console.log('flushQueue');
queue = [];
clearTimeout(drawQueueTimeout);
drawQueueTimeout = -1;
}
function checkQueue () {
console.log('checkQueue', queue.length, drawQueueTimeout);
if (queue.length > 0 && drawQueueTimeout < 0) {
console.log('schedule drawQueue');
drawQueueTimeout = setTimeout(drawQueue, 150);
}
}
function drawQueue () {
drawQueueTimeout = -1;
console.log('draw queue');
if (queue.length > 0) {
var element = queue.shift();
console.log('drawQueue', element.char);
helloPageA.html(helloPageA.html() + element.char);
}
checkQueue();
}
$(window).scroll(function (e) {
var elem = $(".hello-page");
var scrollTop = $(window).scrollTop();
var blockTop = elem.offset().top;
var docHeight = $(document).height();
var windowH = $(window).height();
if (scrollTop + windowH == docHeight) {
// Empty anything typed so far
helloPageA.empty();
flushQueue();
var text = helloPageA.attr("data-text");
helloPageA.text('');
$.each(text.split(''), function (i, letter) {
pushQueue({
char: letter,
index: i
});
});
} else {
helloPageA.empty();
flushQueue();
}
});

(jQuery to Vanilla Javascript) fixed floating element

I am not a big fan of jQuery because it can cause a bigger load time on the page load(even if it's small), so I refrain from using jQuery as much as possible.
I am trying to convert this jQuery code to plain javascript, could someone lead me in the correct direction?
Non-working non-jquery javascript
window.onload = function()
{
var scrolledElement = document.querySelector('#comment');
var top = scrolledElement.offsetTop;
window.scroll(function()
{
var y = window.pageYOffset;
if (y >= top)
{
scrolledElement.classList.add('fixed');
} else {
scrolledElement.classList.remove('fixed');
}
});
});
and this is the actual code for jQuery.
$(document).ready(function () {
var top = $('#comment').offset().top - parseFloat($('#comment').css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
$('#comment').addClass('fixed');
} else {
$('#comment').removeClass('fixed');
}
});
});
Here is what I have so far in jsfiddle. http://jsfiddle.net/knjQh/29/
Update your JS to attach a event on scroll
window.onload = function () {
var scrolledElement = document.querySelector('#comment');
var top = scrolledElement.offsetTop;
var listener = function () {
var y = window.pageYOffset;
if (y >= top) {
scrolledElement.classList.add('fixed');
} else {
scrolledElement.classList.remove('fixed');
}
};
window.addEventListener('scroll', listener, false);
}
Check
http://jsfiddle.net/raunakkathuria/knjQh/33/

Categories

Resources