Improve script of setting height of div by comparing two heights - javascript

I wrote a small script that compares the height of 2 divs and setting the height of the largest to another div.
My question is: how to improve this script?. Because I'm currently repeating the part of getting the hides of the 2 div's
$( document ).ready(function() {
showHeight($( "#tab-content2" ).height());
showHeight($( "#tab-content1" ).height());
});
var bheight = 0;
function showHeight(height) {
if( height > bheight){
bheight = height;
$("aside").height(bheight + 60);
}
}

Select both of of them by selecting all IDs that start with tab-content and then loop over them with .each
$(document).ready(function() {
$("div[id^='tab-content']").each(function(){
showHeight($(this).height());
});
});

i guess kind of this:
$( document ).ready(function() {
showHeight("[id^='tab']"); // pass the selector
});
function showHeight(elem) {
var heights = $(elem).map(function (){
return $(this).height();
}).get(), // loops through the selectors and gets the height in array
maxHeight = Math.max.apply(null, heights); // returns the max height value.
$("aside").height(maxHeight + 60); // and set it here.
}

Add some class to your tabs.
$(document).ready(function () {
var bheight = 0;
$('.tabClass').each(function () {
bheaight = Math.max(bheight, $(this).height());
});
$('aside').height(bheight + 60);
});

Related

Create jQuery infinite loop of items

I am trying to accomplish an infinite loop of items inside 1 main div.
The idea is to show part of the items, then slide the left one outside of the screen, whilst another is added from the right side of the screen.
The following function is working, but the animate method doesn't work, it just changing the css without animating it.
Am I doing it wrong?
Also any better approach would be welcome. I tried to search jQuery solutions but they didn't work well for me so i wanted to create another one.
jQuery(document).ready(function() {
var items = jQuery('.companies-logos div');
var temp;
var item_width = 0;
if(items.length > 9) {
items.slice(9).remove();
setInterval(function(){
jQuery('.companies-logos').append(items[9]);
items[9].style.marginLeft = '0';
item_width = items[0].offsetWidth + 12.5;
jQuery(items[0]).animate({marginLeft: '-' + item_width + 'px'}, 2000);
// items[0].style.marginLeft = '-' + item_width + 'px';
temp = items[0];
jQuery(items[0]).remove();
items.splice(0, 1);
items.push(temp);
// jQuery(items[items.length-1]).css('transition', 'all 2500ms');
}, 2500);
}
});
For those interested in achieving the wanted result from above:
$(function(){
setInterval(function(){
var item_width = $('.companies-logos ul li:first-child').width() + 25;
$(".companies-logos ul li:first-child").animate({"margin-left": -item_width}, 1500, function(){
$(this).css("margin-left",25).appendTo(".companies-logos ul");
});
}, 2000);
});

How to hide each document on window resize?

I am trying to hide each and every element of document when window is resized to some pixels.
This is what i tried to script-
When window is resized to some pixels then each document goes hidden else shown.
I tried implementing this script-
<script type="text/javascript">
$(function () {
var eachdoc=$(document).each();
var docsize = eachdoc.width();
$(window).resize(function () {
$(document).each(function () {
if (docsize > $(window).width()-400) {
$(this).hide();
}
else {
$(this).show();
}
});
});
});
</script>
Well this script is not working, How can i improve this script to hide each element on window resize?
Please suggest !
The basic implementation could be something like
$(function () {
var els=$('.mytable, .mypara');//list of elements
var docsize = eachdoc.width();
$(window).resize(function () {
var cuttoff = $(window).width() - 400;
els.each(function (idx, el) {
var $this = $(this);
if ($this.width() > cuttoff) {
$this.hide();
} else {
$this.show();
}
});
});
});
I'm not certain that this is the best solution or even a good solution, so somebody correct me as needed.. but I'm thinking this way will be a little easier on your cpu.
$.fn.filterNumberRange = function(item, low, high){
return this.filter(function(){
var value = +$(this).attr(item);
return value >= low && value <= high;
});
};
var documents = $('document-selector');
$(documents).each(function(){
$(this).attr('data-width', $(this).width());
});
$(window).resize(function(){
var current-width = parseInt($(window).width()) - 400;
$(documents).filterNumberRange( 'data-width', 0, current-width ).show;
$(documents).filterNumberRange( 'data-width', current-width + 1, 9999 ).hide;
});
Grabbed the filtering function from here:
http://forum.jquery.com/topic/new-attribute-selectors-for-less-than-and-greater-than

scroll other scrollbars with scrollbar

i have 3 divs with scrollbars.
If i scroll in div 1 i want to scroll div 2 and 3 in the opposite direction.
The distance scrolled should be half the distance of div 1.
This is what i have now (small part, rest is in jsfiddle), which works for 1 div.
$("#textBox1").scroll(function () {
console.log("scroll 1");
var offset = $("#textBox1").scrollTop() - scrollPosTBox1;
var half_offset = offset/2.0;
disable1 = true;
if(disable2 == false) {
$("#textBox2").scrollTop(scrollPosTBox2 - half_offset);
}
if(disable3 == false) {
$("#textBox3").scrollTop(scrollPosTBox3 - half_offset);
}
disable1 = false;
});
However, if i try to get the same for the other 2 divs then i can't scroll anything anymore.
This is because div 1 triggers div 2 and div 2 triggers back to div 1 for example.
I tried to fix this with the disable code but it doesn't help.
Can someone help me?
http://jsfiddle.net/XmYh5/1/
No disrespect to #EmreErkan and #Simon for their effort. Here's a no-click version of this.
var $boxes = $("#textBox1,#textBox2,#textBox3"),
active;
$boxes.scrollTop(150);
// set initial scrollTop values
updateScrollPos();
// bind mouseenter:
// 1) find which panel is active
// 2) update scrollTop values
$boxes.mouseenter(function () {
active = this.id;
updateScrollPos();
});
// bind scroll for all boxes
$boxes.scroll(function (e) {
$this = $(this);
// check to see if we are dealing with the active box
// if true then set scrolltop of other boxes relative to the active box
if(this.id == active){
var $others = $boxes.not($this),
offset = $this.scrollTop()-$this.data("scroll"),
half_offset = offset / 2;
$others.each(function(){
$this = $(this);
$this.scrollTop($this.data("scroll") - half_offset);
});
}
});
// utility function:
// assign scrollTop values element's data attributes (data-scroll)
function updateScrollPos() {
$boxes.each(function(){
$this = $(this);
$this.data("scroll",$this.scrollTop());
});
}
Fiddle
You can use a variable to determine active textbox with .mousedown() and do the trick if it's active;
var activeScroll = '';
$("#textBox1").on('mousedown focus mouseenter', function () {
activeScroll = 'scroll1';
}).scroll(function () {
if (activeScroll == 'scroll1') {
console.log("scroll 1");
var offset = $("#textBox1").scrollTop() - scrollPosTBox1;
var half_offset = offset / 2.0;
$("#textBox2").scrollTop(scrollPosTBox2 - half_offset);
$("#textBox3").scrollTop(scrollPosTBox3 - half_offset);
}
});
You can check your updated jsFiddle here.
Finally got a dynamic solution for this, was more complex than I thought but I think I got it:
http://jsfiddle.net/XmYh5/14/
var initialTop = 150,
factor = 2;
$(".textBox")
.addClass('disabled')
.scrollTop(initialTop)
.on('scroll', function () {
var $this = $(this);
if(!$this.is('.disabled')) {
this.lastOffset = this.lastOffset || initialTop;
var offset = $this.scrollTop(),
step = (offset - this.lastOffset) / factor;
$this.siblings().each( function() {
var $this = $(this),
offset = $this.scrollTop() - step;
$this.scrollTop(offset);
this.lastOffset = offset;
});
this.lastOffset = offset;
}
})
.on('mouseenter', function() {
$(this).removeClass('disabled').siblings().addClass('disabled');
});

.next() not working as intended

So,
if($(this).hasClass('active')){
$(this).removeClass('active');
$(this).prev().addClass('active');
}
works fine, it adds the class "active" to this previous div of the same kind.
if($(this).hasClass('active')){
$(this).removeClass('active');
$(this).next().addClass('active');
}
However, adds the class to the next div (as i intend for it to do) for about 0.5 of a second BUT then removes it.
Here's ALL of the jQuery (as per your comments below) - Please do not comment on my horrible code organization
$(window).load(function () {
// Initial variables
var numberSlides = 0;
var currentSlide = 1;
var ready = true;
var pageWidthR = $(document).width() - 352;
var pageWidthL = $(document).width() - 352;
// Update number of slides by number of .slide elements
$('#features-slider .slide').each(function () {
numberSlides++;
});
// Go through each slide and move it to the left of the screen
var i = 0;
$($('#features-slider .slide').get().reverse()).each(function () {
if (i == 0) {
} else {
var newWidth = i * 115;
$(this).css('left', '-' + newWidth + '%');
}
i++;
});
// Animate the first slide in
$('#features-slider .slide:last-child').addClass('active').animate({
left: 0
}, 1500);
// Remove the loading message
$('#loading').fadeOut(1000, function () {
$('#loading').remove();
// Now that we're done - we can show it
$('#features-slider').show();
});
/***** Left and Right buttons *****/
/* Right */
$('#rightbutton').click(function () {
var numberSlides = 0;
$('#features-slider .slide').each(function () {
numberSlides++;
});
var index = $('.slide.active').index() + 1;
if (!$('.slide').is(':animated') && index != 1) {
$('#features-slider .slide').each(function () {
if ($(this).hasClass('active')) {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) + 115;
} else {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) + 115;
}
$(this).animate({
left: newLeft + '%'
}, 1500);
if ($(this).hasClass('active')) {
$(this).removeClass('active');
$(this).prev().addClass('active');
}
});
}
});
/* Left */
$('#leftbutton').click(function () {
var numberSlides = 0;
$('#features-slider .slide').each(function () {
numberSlides++;
});
var index = $('.slide.active').index() + 1;
if (!$('.slide').is(':animated') && index != numberSlides) {
$('#features-slider .slide').each(function () {
if ($(this).hasClass('active')) {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) - 115;
} else {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) - 115;
}
$(this).animate({
left: newLeft + '%'
}, 1500);
if ($(this).hasClass('active')) {
$(this).next().addClass('active');
$(this).removeClass('active').not($(this).next());
}
});
}
});
});
$(document).ready(function () {
// Hide the slider and show a loading message while we do stuff and the images / DOM loads - Also disable overflow on the body so no horizontal scrollbar is shown
$('body').css('overflow-x', 'hidden');
$('#features-slider').hide();
$('#loading').html('<center> <img id="loader" src="/wp-content/themes/responsive/library/images/ajax-loader.gif" /> Loading</center>');
});
RESOLVED
New left button function :
$('#leftbutton').click(function(){
var numberSlides = 0;
$('#features-slider .slide').each(function(){
numberSlides++;
});
var index = $('.slide.active').index()+1;
if( !$('.slide').is(':animated') && index != numberSlides ){
var done = false;
$('#features-slider .slide').each(function(){
if($(this).hasClass('active')){
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft)-115;
} else {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft)-115;
}
$(this).animate({left: newLeft+'%'}, 1500);
if($(this).hasClass('active') && done == false){
$(this).next().addClass('active');
$(this).removeClass('active');
done = true;
}
});
});
If you're iterating forward through the elements, then it should be clear what's going on - you add the "active" class to the next element, and then the next iteration takes it away.
This is just a guess however as you did not post enough code for me (or anybody else) to be sure.
edit — ok now that you've updated the question, it's clear that the guess was correct. The .each() function will iterate forward through the elements. When an element has the "active" class, and the code removes it and adds it to the next element, then on the next iteration the work is undone.
Since you are referencing this and by the behavior you're describing, you are likely iterating a loop for a list of elements. As a result, you are completing the action you want but the next iteration is removing the previous changes due to your usage of removing a class and then adding the class back.
As it stands now, your code does not illustrate how this occurence can be happening.
Update:
As suspected, you seem to be looping as signified by: each(function(){. While iterating through your objects the class is being pushed forward and is not acting as desired. You are stating add the class to the next element, but remove it from the current element, and this behavior continues through your iteration.
On a side note, update your code to call removeClass() on the current object first, before adding it to the next object:
if ($(this).hasClass('active')) {
$(this).removeClass('active').next().addClass('active');
}

How can I say "if width > height" then "do this" with jQuery?

I have a few elements. The number of them on the page changes constantly, keep that in mind.
The element is called .portalimg. I need to say if the width > height, set it's width to 125px. If the height > width, set the height to 125px.
Here's what I have:
$('.portalimg').each(function() {
var pimgw = $(this).width();
var pimgh = $(this).height();
if (pimgw > pimgh) {
$(this).css('width','125px')
} else {
$(this).css('height','125px')
}
});
EDIT: It alerts success but doesn't apply the width & height.
Where did I go wrong?
EDIT 2: Updated code with cleanest from below. That still only constrains the height property, even if the images is taller then it is wide. Take a look:
http://jacksongariety.com/gundoglabs/
EDIT 3: The issue is they all return 0. If I have an alert say the value of pimgw or pimgh, it's always 0.
EDIT 4: Finally got the best, cleanest code possible with caching and it'll always load correctly, even if it draws images form the cache:
$(function(){
$('.portalimg').ready(function(){
$('.portalimg').fadeTo(0,1).each(function(index) {
var a = $(this);
if (img.width() > a.height()) {
a.css('width','135px')
} else {
a.css('height','125px')
}
});
});
});
If there are multiple elements of class portalimg you could simply use a .each iterator: http://api.jquery.com/each/
$(function() {
$('.portalimg').each(function(index) {
var img = $(this);
if (img.width() > img.height()) {
img.css('width','125px')
} else {
img.css('height','125px')
}
});
}
$('.portalimg').each(function() {
var pimgw = $(this).width();
var pimgh = $(this).height();
if (pimgw > pimgh) {
$(this).css('width','125px')
} else {
$(this).css('height','125px')
}
});
How about this:
$('.portalimg').each(function() {
(($(this).width() > $(this).height())
&& ($(this).css('width','125px')) )
|| ($(this).css('height','125px'))
});
http://jsfiddle.net/DerekL/Qx4jF/
Your loop is wrong you should use
pimg = $('.portalimg').each( function() {;
alert("success")
var pimgw = $(this).width();
var pimgh = $(this).height();
if (pimgw > pimgh) {
$(this).css('width','125px')
} else {
$(this).css('height','125px')
}
});
This call a function on all find object with the class '.portalimg' in your document.
$('.portalimg').each(function() { var
img = $(this),
w = img.width(),
h = img.height(),
toModify = w > h ? 'width' : 'height';
img.css(toModify, '125px');
}
Might try this. Other answers are excellent to. You went wrong with the syntax of for and with body. Did you mean #body or .body?
$(".portalimg").each(function(){
var pimgw = $(this).width(),
pimgh = $(this).height();
if (pimgw > pimgh) {
$(this).css('width','125px')
}else{
$(this).css('height','125px')
}
});

Categories