I'm having a problem with resizing an element using JavaScript and the Zepto library. When the page loads the element gets the window width and height just fine. I have also tested my window.resize with an alert() and that works fine too. My problems occurs when I try and resize the element as the window changes size. Here is my JavaScript which is loaded through Modernizr:
$(document).ready(function()
{
setTimeout(function(){
window.scrollTo(0, 1);
}, 0);
var navConfig =
{
winWidth : $(window).width(),
winHeight : $(window).height(),
primaryNav : $('#primaryNav'),
openPrimaryNav : $('#openPrimaryNav'),
closePrimaryNav : $('#closePrimaryNav')
}
function sizePrimaryNavigation()
{
navConfig.primaryNav.css(
{
'height' : navConfig.winHeight - 5,
'width' : navConfig.winWidth - 20
});
}
function primaryNavigation()
{
navConfig.openPrimaryNav.bind('click', function()
{
navConfig.primaryNav.addClass('open');
});
navConfig.closePrimaryNav.bind('click', function()
{
navConfig.primaryNav.removeClass('open');
});
}
sizePrimaryNavigation();
primaryNavigation();
window.onresize = sizePrimaryNavigation;
});
I have also set up a working demo - http://jsfiddle.net/nicklansdell/DWbNS/2/ Click the menu button on the demo for the element I am trying to resize.
Can anyone tell me what I am doing wrong please? Many thanks in advance.
I checked, write the function like this, it will work.
demo is here
http://jsfiddle.net/DWbNS/7/
http://jsfiddle.net/DWbNS/9/
and by the way,zepto doc says "bind" is "Deprecated, use on instead."
function sizePrimaryNavigation()
{
navConfig.primaryNav.css(
{
'height' : win.width() - 5,
'width' : win.height() - 20
});
}
$(window).resize(sizePrimaryNavigation);
// window.onresize = sizePrimaryNavigation;
// will work too
You are assigning the onresize property to a jQuery object ($(window)). You MUST assign it to window.onresize instead.
Related
I have added a windows resize event on my page
it is called whenever page size is changed.
but when I update css values for a div element inside page using jquery css and animate it automatically triggers windows resize event.
this happens only for IE
I want to prevent resize event from executing on manual change of size by animate or css methods
Here is my code
for window resize
window.onresize=function(){ ... };
for div size change
$('div#divtest').css({ 'position': 'absolute', 'z-index': '1', 'background-color': '#f6f6f6' }).animate({
width: '20%',
height : $('div#divother').height() - 29
}, 0);
EDIT:
i do not want to make any change in resize event reason is it is page wise different so i have to make change in all existing events
any chance i can temporary turn it off
You can achieve this by following way:
Before applying css animation set some flag like following:
$('div#divtest').data("css_animation", true); //set the flag
$('div#divtest').css({ 'position': 'absolute', 'z-index': '1', 'background-color': '#f6f6f6' }).animate({
width: '20%',
height : $('div#divother').height() - 29
}, 0,function() {
// Animation complete.
$('div#divtest').data("css_animation", false); //reset the flag
});
And in resize we can check whether flag is set or not as follows:
window.onresize=function(){
var flagValue = $('div#divtest').data("css_animation"); //fetch the flag value
//don't do anything if resize is getting called via css animation
if(flagValue === true)
return;
...
};
Finally i solved this.
thanks to vijayP for flag suggestion.
but instead of puting flag in each resize function i just override window.onresize function
i add following code in master page script /general script
(function($) {
var oldresize = window.onresize;
window.onresize = function() {
if (CallPageResize)
return oldresize.call(this);
};
})(jQuery);
where CallPageResize is flag and its value is set as follow
CallPageResize = false; $('div#divtest').css({ 'position': 'absolute', 'z-index': '1', 'background-color': '#f6f6f6' }).animate({
width: '20%',
height: $('div#divother').height() - 29
}, 0);
CallPageResize = true;
To avoid unnecessary window resize event, compare the previous window width and height and proceed the window resize event if width or height differs. This is only a workaround solution.
private previousWindowWidth = 0; private previousWindowHeight = 0;
private onWindowResize(): void {
var windowWidth = window.innerWidth;
var windowHt = window.innerHeight;
if (previousWindowWidth === windowWidth && previousWindowHeight ===
windowHt ) {
return;
}
previousWindowWidth = windowWidth ;
previousWindowHeight = windowHt ;
// continue with other operations
..................................
}
I have this slider on my WP page, which is vertical. I would like to convert it so it his horizontal. As I understood I need to change my JS code.
jQuery(function($) {
var image_es;
var zoom_timer;
var win_width = 0;
function resize_venedor_thumbs() {
if (win_width != $(window).width()) {
if (image_es) {
image_es.destroy();
}
image_es = $('#thumbnails-slider-756').elastislide({
orientation : 'vertical',
minItems: 4
});
win_width = $(window).width();
}
if (zoom_timer) clearTimeout(zoom_timer);
}
$(window).load(resize_venedor_thumbs);
$(window).resize(function() {
clearTimeout(zoom_timer);
zoom_timer = setTimeout(resize_venedor_thumbs, 400);
});
});
I tried to change vertical to horizontal in inspect element mode but it did not change at all.
If you change the orientation to 'horizontal' in inspect element mode, you need to make sure the resize_venedor_thumbs function is called.
It looks like it is called on load or resize (try resize because loading will erase your edits); or you can call it in the console yourself resize_venedor_thumbs(); or, of course, edit the source and load the page.
I'm not sure how to use the order of the window events load and resize on jQuery to make it work when resizing. The first function is used to get the total width except the scrollbar width, because the CSS is using the device width, but the JS is using the document width.
The second function adds a style when the total screen width is between 768px and 1024px, and it should work when I load the page at any screen, after resizing, etc. I'm doing a lot of tests and I think the problem is about the window events order.
For being more specific about the problems, it doesn't remove the style when I load the page at 900px and I expand it to > 1024px! Or by the contrary, it doesn't add the style when I load the page at 1300px and I shorten the width to 900px.
I think it's 'cause of the load and resize events order, but I'm not totally sure. Or maybe I'm not doing the correct declaration of the variable into the resize.
The code:
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
$(document).ready(function(){
var vpwidth=$(window).width();
$(window).on('resize', function(){
var changeWidth = (($('.main-content .wrap').width() * 96.3)/100) - 312;
if(vpwidth >= 768 && vpwidth <= 1024) {
$('.contentleft, .contentright').css('width', changeWidth + 'px');
} else {
$('.contentleft, .contentright').removeAttr('style');
}
}).resize();
});
I believe the issue is that you're not re-calculating the vpwidth on resize, So the value you got when the page was loaded will be used every time window is resized.
try
$(document).ready(function(){
$(window).on('resize', function(){
var vpwidth=$(window).width(); // get the new value after resize
var changeWidth = (($('.main-content .wrap').width() * 96.3)/100) - 312;
if(vpwidth >= 768 && vpwidth <= 1024) {
$('.contentleft, .contentright').css('width', changeWidth + 'px');
} else {
$('.contentleft, .contentright').removeAttr('style');
}
}).resize();
});
The issue is because you are not recalculating the width (vpwidth) on resize function.
It is initialized and set on page load itself and hence doesn't change when the window is resized causing the style to not be added or removed.
You need to re-assign the value to the variable from within the resize function.
$(window).on('resize', function(){
var vpwidth=$(window).width();
}
Demo Fiddle
I just found this tutorial on making an image cross fade transition with jquery.
The demo page works perfectly (jquery 1.2.3 used).
But when I apply the code to my site (jquery 10.1.0 embedded) it is not working...
When I embed the 1.2.3 version it works.
Anyone an idea whats wrong with the code?
here it comes:
// wrap as a jQuery plugin and pass jQuery in to our anoymous function
(function ($) {
$.fn.cross = function (options) {
return this.each(function (i) {
// cache the copy of jQuery(this) - the start image
var $$ = $(this);
// get the target from the backgroundImage + regexp
var target = $$.css('backgroundImage').replace(/^url|[\(\)'"]/g, '');
// nice long chain: wrap img element in span
$$.wrap('<span style="position: relative;"></span>')
// change selector to parent - i.e. newly created span
.parent()
// prepend a new image inside the span
.prepend('<img>')
// change the selector to the newly created image
.find(':first-child')
// set the image to the target
.attr('src', target);
// the CSS styling of the start image needs to be handled
// differently for different browsers
if ($.browser.msie || $.browser.mozilla) {
$$.css({
'position' : 'absolute',
'left' : 0,
'background' : '',
'top' : this.offsetTop
});
} else if ($.browser.opera && $.browser.version < 9.5) {
// Browser sniffing is bad - however opera < 9.5 has a render bug
// so this is required to get around it we can't apply the 'top' : 0
// separately because Mozilla strips the style set originally somehow...
$$.css({
'position' : 'absolute',
'left' : 0,
'background' : '',
'top' : "0"
});
} else { // Safari
$$.css({
'position' : 'absolute',
'left' : 0,
'background' : ''
});
}
// similar effect as single image technique, except using .animate
// which will handle the fading up from the right opacity for us
$$.hover(function () {
$$.stop().animate({
opacity: 0
}, 250);
}, function () {
$$.stop().animate({
opacity: 1
}, 250);
});
});
};
})(jQuery);
// note that this uses the .bind('load') on the window object, rather than $(document).ready()
// because .ready() fires before the images have loaded, but we need to fire *after* because
// our code relies on the dimensions of the images already in place.
$(window).bind('load', function () {
$('img.fade').cross();
});
html is that:
<img class="fade" src="original.jpg" style="background: url(hover.jpg);" />
heres the link to the tutorial (dated 2008):
http://jqueryfordesigners.com/image-cross-fade-transition/
$.browser is not supported by new version of jQuery.
I'm creating a gallery for a responsive lay-out - I am using jQuery Riding Carousels for the thumbnails.
When the window is re-sized to smaller than 1024px, the orientation of the carousel needs to change from vertical to horizontal ...
I'm doing it like this at present:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#mycarousel').jcarousel({
vertical: $(window).width() > 1008,
scroll: 3,
});
});
</script>
... the JS simply hooks up a class, but it doesn't do so if you re-size the browser window by dragging it - you need to refresh the page.
Is there a way to destroy the script and re-initialize it on the fly?
Please check Working exmpale: http://codebins.com/bin/4ldqpba/1/Jcarousel%20vertical%20on%20resize
Tested in all browsers and works perfectly fine. bounty is mine :)
In the example i have give threshold widht 350 you can test it by resizing the result pane and as soon as you start havin horizontal scroll bar it will converted to vertical.
1 possible issue depending on your requirement is if you ahve any handlers on images they will be gone after changing display way. the solution for it is wrap your #mycarousel in a div and use Jquery delegate to handle events on the wrapper so no issue with events also.
Let me know if you come under this situation.
Following code is exactly as per your need.
When the window is re-sized to smaller than 1024px, the orientation of the carousel needs to change from vertical to horizontal .
which is revers form the example as for me it makes more sense if width is less make it vertical.
jQuery(document).ready(function() {
var widthCheck = 1008;
var resizeTimer = null,
verticalFlg = $(window).width() > widthCheck;
var obj = jQuery('#mycarousel').clone();
$('#mycarousel').jcarousel({
vertical: verticalFlg,
scroll: 2
});
jQuery(window).resize(function() {
resizeTimer && clearTimeout(resizeTimer); // Cleraring old timer to avoid unwanted resize calls.
resizeTimer = setTimeout(function() {
var flg = ($(window).width() > widthCheck);
if (verticalFlg != flg) {
verticalFlg = flg;
$('#mycarousel').closest(".jcarousel-skin-tango").replaceWith($(obj).clone());
$('#mycarousel').jcarousel({
vertical: verticalFlg,
scroll: 2
});
}
}, 200);
});
})
Or you can look at the source. I'm guessing you are using version 0.2
Looking at the source
https://github.com/jsor/jcarousel/blob/0.2/lib/jquery.jcarousel.js
we can see that there are two lines (80 and 81) which are only done in object init. Those lines are
this.wh = !this.options.vertical ? 'width' : 'height';
this.lt = !this.options.vertical ? (this.options.rtl ? 'right' : 'left') : 'top';
also this line at 149
if (!this.options.vertical && this.options.rtl) {
this.container.addClass('jcarousel-direction-rtl').attr('dir', 'rtl');
}
It might be if you add those to the callback you will get better results.
You could also try version 0.3 of the plugin.
Prior answer:
Can't test it myself right now, but try this:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#mycarousel').jcarousel({
vertical: $(window).width() > 1008,
scroll: 3,
reloadCallback: function () {
this.options.vertical = $(window).width() > 1008;
},
});
});
</script>
<script type="text/javascript">
jQuery(document).ready(function() {
var sizeCheck = function() {
return $(window).outerWidth() >= 1024
}
jQuery('#mycarousel').jcarousel({
vertical: sizeCheck(),
scroll: 3,
});
var jCarousel = jQuery('#mycarousel').data('jcarousel');
window.onresize = function() {
jCarousel.options.vertical = sizeCheck(); // maybe you have to access the option through jCarousel.plugin.options.vertical
jCarousel.reset();
}
});
</script>
Maybe this works.
I haven't tested the following code, but I am fairly sure the following code should work:
<script type="text/javascript">
var carousel;
jQuery(window).resize(function() {
if(carousel !== undefined) carousel.destroy();
carousel = jQuery('#mycarousel').jcarousel({
vertical: $(window).width() > 1008,
scroll: 3,
});
});
</script>
or even better something along the lines of:
<script type="text/javascript">
var carousel;
jQuery(document).ready(function() {
carousel = jQuery('#mycarousel').jcarousel({
vertical: $(window).width() > 1008,
scroll: 3,
});
});
jQuery(window).resize(function() {
//NOT SURE WHICH OF THE BELOW LINES WOULD WORK, try both and check which works
carousel.options.vertical = $(window).width() > 1008;
carousel.vertical = $(window).width() > 1008;
carousel.reload();
});
</script>
If it does not, you should add a console.log(carousel) to your code and check out what the prototype is of the outputted value (check F12). There should be something along the lines of destroy (or alternatively check console.log($.jcarousel())).