Javascript only works after page refresh - javascript

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

Related

jQuery: clone div multiple times on scroll

I'm trying to figure out how to repeatedly clone the contents of a div on scroll, thus giving the impression that the page goes on forever and ever. My markup thus far is as follows and a fiddle here too https://jsfiddle.net/guht49La/:
var inserated = false
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800 && inserated == false) {
var $button = $('.hd').clone();
($button).insertBefore('.ap');
inserated = true;
} else {
}
});
Although this only inserts it once, as I want to keep inserting it every 800px (for example) thus giving the impression that the page goes on forever and ever. Any suggestions on this would be greatly appreciated!
This will work
var inserated = false
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800) {
var $button = $('.hd').clone();
($button).insertBefore('.ap');
inserated = true;
} else {
}
});
This is a complete guess, but perhaps give this a go:
var nextInsert = 800;
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= nextInsert) {
var $button = $('.hd').clone();
($button).insertBefore('.ap');
nextInsert += 800;
} else {
}
});
It is working, but it clones the div just once because you changed the inserated variable to true after inserting the first clone. It will work indefinitely if you delete it:
var inserated = false
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800 && inserated == false) {
var $button = $('.hd').clone();
($button).insertBefore('.ap');
// inserated = true;
} else {
}
});
Notice that inserated = true; is commented out.
That code, however, can (and almost certainly) creates a huge amount of clones, so I'd suggest controlling the scrolling insertion point using something along the lines of Nat Karmios answer
My suggestion is similar to jbmartinez answer, except I would drop the inserated variable altogether and use classes to determine elements to be cloned:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800) {
var $button = $('.hd').not(".cloned").clone();
$button.addClass("cloned");
($button).insertBefore('.ap');
} else {
}
});
Would still need to adjust the scrolling mark as noted above tho.

$(window).resize conditional = if page is less than

I want to move an element (div) in the dom from one place to another using jQuery. I have the code working almost too well, in that it's appending my code every single time the browser is resized and then carries on until the browser crashes.
Here's my code:
$(window).resize(function() {
var bodyWidth = $(window).width();
if(bodyWidth < 740){
$('.GalleryHeader').appendTo('li');
}
});
How do I get this to only run once, so it only does the one time, and then perhaps put it back into it's original location in the dom when resizing back up over 740px.
Try
jQuery(function () {
var flag;
$(window).resize(function () {
var bodyWidth = $(window).width();
console.log(bodyWidth)
if (flag !== false && bodyWidth < 740) {
//move the element to new location
console.log('less')
flag = false;
} else if (flag !== true && bodyWidth >= 740) {
//put it back to original location
console.log('more')
flag = true;
}
}).resize();
})
Demo: Fiddle

JavaScript is being triggered before its time, *only on Chrome & IE

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;

if element exist on document then add an addittional value into method

I really need some help with this, I dont know javascript well at all to be honest, a friend of mine put some of this together a few months ago ive just added $contentContainer and added these variables but I just need one more thing added to if for it to suite my needs...
<script type="text/javascript">
// DOM Container Resize Handler
var adjustStyle = function() {
var winWidth = $(window).width(),
width = parseInt(winWidth),
container = $('body .fixed');
contentContainer = $('body .content');
if (width >= 1454) {
container.css('width','1454px');
contentContainer.css('width','1210px');
} else if ((width < 1454) & (width >= 1212)) {
container.css('width','1212px');
contentContainer.css('width','968px');
} else {
container.css('width','970px');
contentContainer.css('width','726px');
}
};
$(function() {
var filterWrap = $("#filterWrap"),
offset = filterWrap.offset(),
topPadding = 15;
$(window).scroll(function() {
if ($(window).scrollTop() > offset.top) {
filterWrap.stop().animate({
marginTop: $(window).scrollTop() - offset.top + topPadding
});
} else {
filterWrap.stop().animate({
marginTop: 0
});
};
});
// DOM Container Resize Handler - Initialization
$(window).resize(function() {
adjustStyle();
});
adjustStyle();
});
</script>
I need to modify this script to search through the document and IF document DOES NOT contain ('body .asideContent') to add 252px to the object contentContainer.css method
Don't worry about the fileerWrap function this works fine :)
I really appreciate the help
Should be something like this :)
if($("body.asideContent").length === 0){
var width = contentContainer.css('width');
contentContainer.css('width',width + 252 + "px");
}

Have font size change according to size of div

I have a resisable div with text inside. I want the text to scale as the div changes size.
Specifically, I want the text to have the largest possible font size that will make it fit inside the div.
Use FitText http://fittextjs.com/
I use this plugin that I made based on fitText.js, because fitText doesn't fit my needs, due to I don't know the length of the strings to resize, so the fix resize parameter of fitText don't work in all cases.
$.fn.adjustTextSize = function (set_max_size, min_size) {
min_size = min_size || 12; // if no value then set a default one
var string, width, line, initFontSize, returnFontSize, ratio;
return this.each(function() {
// Store the object
var $this = $(this);
var resizer = function () {
string = $this;
string.html('<span style="white-space: nowrap;">' + string.html() + '</span>');
width = string.width();
line = $(string.children('span'));
initFontSize = parseInt(string.css('font-size'));
ratio = width/line.width();
returnFontSize = initFontSize*ratio;
if (set_max_size && returnFontSize > initFontSize) {
returnFontSize = initFontSize;
}
if (min_size && returnFontSize < min_size) {
returnFontSize = min_size;
}
string.css('font-size',returnFontSize);
while (line.width() >= width) {
if (min_size && returnFontSize <= min_size) {
string.html(line.html());
return false;
}
string.css('font-size', --returnFontSize);
}
string.html(line.html());
}
// Call once to set.
resizer();
// Call on resize. Opera debounces their resize by default.
$(window).on('resize orientationchange', resizer);
});
};
$('.js-adjust-text').adjustTextSize(false, 12);
$('.js-adjust-text-limit').adjustTextSize(true, 30);
This plugin get two parameters:
set_max_size: boolean to limit maximum font size to its defined size in CSS
min_size: Integer number to limit minimum font size.
I hope it works for your case.
You can try like this:
If you want the height to adjust, try setting the height to auto
$("#sample").modal({
containerCss:{
backgroundColor:"#fff",
borderColor:"#0063dc",
height:450,
padding:0,
width:830
}
});
here is a little changed code above, because it is for getting width of container I made edit for heigh container adjustment.
$.fn.adjustTextSize = function (set_max_size, min_size) {
min_size = min_size || 12; // if no value then set a default one
var string, height, line, initFontSize, returnFontSize, ratio;
return this.each(function() {
// Store the object
var $this = $(this);
var resizer = function () {
string = $this;
string.html('<span>' + string.html() + '</span>');
height = string.height();
line = $(string.children('span'));
initFontSize = parseInt(string.css('font-size'));
ratio = height/line.height();
returnFontSize = (initFontSize*ratio) ;
if (set_max_size && returnFontSize > initFontSize) {
returnFontSize = initFontSize;
}
if (min_size && returnFontSize < min_size) {
returnFontSize = min_size;
}
string.css('font-size',returnFontSize);
while (line.height() >= height) {
if (min_size && returnFontSize <= min_size) {
string.html(line.html());
return false;
}
string.css('font-size', --returnFontSize);
}
string.html(line.html());
}
// Call once to set.
resizer();
// Call on resize. Opera debounces their resize by default.
$(window).on('resize orientationchange', resizer);
});
};
Hope it will useful

Categories

Resources