Calculate largest width of a set of elements using jQuery - javascript

I have made a quick Jsbin: http://jsbin.com/ujabew/edit#javascript,html,live
What i'm trying to achieve is to find out which is the largest <section> out of the 3 from the link. So what i'd like is to, after the loop runs, is to have var width set to the largest possible number that any of the widths could be.
Code in progress posted in link

Here:
var maxWidth = Math.max.apply( null, $( elems ).map( function () {
return $( this ).outerWidth( true );
}).get() );
Live demo: http://jsfiddle.net/rM4UG/

Fleshing out Marc B's comment, using Math.max():
$(document).ready(function(){
var maxWidth = 0;
$('.content ul li').each(function(){
var itemWidth = $(this).outerWidth(true);
maxWidth = Math.max(maxWidth, itemWidth)
});
});

I believe you want to look into the underscore library. Specifically, the max method

$(document).ready(function(){
var maxWidth = 0;
$('section').each(function(){
w = $(this).outerWidth(true);
if ( w > maxWidth)
maxWidth = w;
});
});

Change the .each() loop to this:
var thisWidth = $(this).outerWidth(true);
if (thisWidth > width) {
width = thisWidth;
}

I have just written a function regarding this. I thought it might help others. (jQuery)
$.fn.largerWidth = function () { //function(p)
// where 'p' can be clientWidth or offsetWidth
// or anything else related to width or height
var s = this,m;
for (var i = 0; i < s.length; i++) {
var w = s[i].offsetWidth; // s[i][p];
(!m || w > m) ? (m = w) : null
}
return m;
}

This was my idea:
$(document).ready(function () {
var elements = $(".content ul li");
var count = elements.length - 1;
var width = [];
elements.each(function (n) {
width.push($(this).outerWidth(true));
if (count == n) {
width = Math.max.apply(Math, width);
}
});
});
I added the count of the number of elements and then runs the Math.max to get the largest number when each loop is done.

Related

How to add a class to a each li whenever you scroll to it with jquery

I have a list with many li
I'd like to add a class to each li only when I scroll to that specific li
The issue is the class is added to every li once I scroll to only 1 of them
$(window).scroll(function(e) {
var y = $(document).scrollTop();
var h = $(window).height();
var t = $('li.product');
var length = t.length;
for(var i=1;i <= length;){
var number = 'li.product:nth-child('+i+')';
if(y + h > $(number).position().top){
$(number).addClass("animate__animated animate__fadeInDown");
}
i++;
}});
Thanks in Advance
I couldn't find what's wrong with your code so I made another version of your code. You can find it at https://codepen.io/beneji/pen/RwLQLVV.
The code uses .each instead of a for loop which is a better fit in this case.
You can adjust this code to your particular case.
$(window).scroll(function(){
const scrolling_position = $(window).scrollTop()
const window_height = $(window).height()
$("li.product").each(function(){
const product_position = $(this).position().top
if(product_position <= scrolling_position + window_height)
$(this).addClass("animate__animated animate__fadeInDown") // replace this by whatever class you want
});
})
Consider the following.
$(window).scroll(function(e) {
var y = $(document).scrollTop();
var h = $(window).height();
var t = $('li.product');
t.each(function(i, el) {
if ((y + h) > $(el).position().top) {
$(el).addClass("animate__animated animate__fadeInDown");
}
});
});
This is untested as you did not provide a Minimal, Reproducible Example.
Using .each() we can iterate each of the elements. i is the Index and el is the Element itself.

jQuery to find height of H3 after each prepend has added them all

Any ideas what I am doing wrong here? I have tried adding within the each as well but ended up being like 415px in height which was incorrect as only 2 lines of text so should be around 40px.
As you will see it creates the H3 heading in the each, but what I need to do after the the each is complete is find the highest heading so I can then set the height of all the others.
$(document).ready(function() {
// rebuild product options display
$('.rebuild_options .ty-product-options .ty-product-options__item').each(function(i, obj) {
var option_title = $(this).find('.ty-product-options__item-label').text().replace(":", "");
var option_html = $(this).find('.ty-product-options__item-label span a').attr('title');
var $option_content = $(option_html);
var option_html_text = $option_content[0].innerHTML;
var option_html_img = $option_content[1].innerHTML;
$(this).find('.ty-product-options__box').hide();
$(this).find('.ty-product-options__item-label').addClass('input-text cm-hint');
$(this).find('.ty-product-options__item-label').attr('title',option_html_text);
$(this).find('.ty-product-options__item-label').html(option_html_img);
$(this).find('.ty-product-options__item-label').prepend('<i class="option-status-icon ty-icon-star-empty"></i>');
$(this).find('.ty-product-options__item-label').prepend("<h3 class='option-heading'>"+option_title+"</h3>");
});
var maxHeight = 0;
$('.ty-product-options__item-label h3').each(function(i, obj) {
if ($(this).height() > maxHeight) {
maxHeight = $(this).height();
}
$(this).height(maxHeight);
});
});
$('.ty-product-options__item-label h3').each(function(i, obj) {
if ($(this).height() > maxHeight) {
maxHeight = $(this).height();
}
}).height(maxHeight);
You should assign the height to all h3's after calculating max by chaining it after the each function.

I have to read Coordinates of childs div in jquery and i want to sort out by x coordinates my code is below

The current way is providing invalid output.
This is the object i'm trying to sort through
please check it
$('.childboxes').each(function () {
var divs = $(this);
var divID = $(this).attr('id');
var position = divs.position();
var left = position.left;
var top = position.top;
AllDivsCoor.push({ "id": divID, "leftcoor": left, "topcoor": top });
});
AllDivsCoor.sort('leftcoor');
You've to write a own sort function like this:
function compareCoords(a, b) {
if (a.leftcoor < b.leftcoor) return -1;
if (a.leftcoor > b.leftcoor) return 1;
return 0;
}
AllDivsCoor.sort(compareCoords);
DEMO: JSFiddle
Further informations about sort()

position() being treated as a function

I am working on a slider, here is the code for it:
$(document).ready(function() {
// MAKE SLIDER WIDTH EQUAL TO ALL SLIDES WIDTH
var totalWidth = 0;
$('.slide').each(function() {
totalWidth = totalWidth + $(this).outerWidth(true);
});
var maxScrollPosition = totalWidth - $(".slider_wrap").outerWidth();
function slideMove($targetSlide) {
if ($targetSlide.length) {
var newPosition = $targetSlide.position().left;
if (newPosition <= maxScrollPosition ) {
$targetSlide.addClass('slide--active');
$targetSlide.siblings().removeClass("slide--active");
$(".slider").animate({
left : - newPosition
});
}
else {
$(".slider").animate({
left : - maxScrollPosition
});
};
};
};
$(".slide").width(totalWidth);
$(".slide:first").addClass("slide--active");
$(".next_post").click(function(){
var $targetItem = $(".slide--active").prev();
slideMove('.slide');
});
$(".prev_post").click(function(){
var $targetItem = $(".slide--active").next();
slideMove('.slide');
});
});
While I would expect this to work, I am getting an error that says: TypeError: $targetSlide.position is undefined. From the if statement in the function slideMove. Why doesn't this work? I am still learning jQuery so sorry if it is an obvious answer.
change this
slideMove('.slide');
to this
slideMove($('.slide'));
In your method slideMove you are expecting a JQUERY DOM ELEMENT where as you are giving it just a STRING which is class name of that particular DOM element
YO! you change it to this
...
$('.next_post').click(function(){
var $targetItem = $('.slide--active').prev();
slideMove($('.slide'));
});
$('.prev_post').click(function(){
var $targetItem = $('.slide--active').next();
slideMove($('.slide'));
});
...

Append to one of two columns, then other column

The following code sorts the .dataCard elements by the data-cardNumber attribute's values and then appends them in the order to #main.
How can I append them to the #left or #right?
How I want it to decide between #left or #right is to measure the height of both #left and #right and compare them.
If #left is taller / longer then append to #right, if #right is taller / longer then append to #left, and if they are both the same height then append to #left.
var m = $('#main .dataCard').sort(function(a, b){
return $(a).data('cardnumber') - $(b).data('cardnumber');
}).appendTo('#main');
I would greatly appreciate any and all help in achieving this sorting into one column or the other based on height.
Thanks in Advance!
}
fiddle Demo
var left = $('#left'), //cache selector
right = $('#right'), //cache selector
append_to_div;
if (left.height() < right.height()) { //compare height
append_to_div = right;
} else {
var append_to_div = left;
}
var x = $('#main .dataCard').sort(function (a, b) {
return $(a).data('cardnumber') - $(b).data('cardnumber');
});
append_to_div.html(x); //html will add new list of items where as append will add items top previous elements
Updated after OP's comment
Updated fiddle Demo
var left = $('#left'),
right = $('#right'),
l = [],
r = [];
var x = $('#main .dataCard').sort(function (a, b) {
return $(a).data('cardnumber') - $(b).data('cardnumber');
});
for (var i = 0; i < left.children().length; i++) {
l.push(x[i]);
}
for (var i = left.children().length; i < left.children().length + right.children().length; i++) {
r.push(x[i]);
}
left.html(l);
right.html(r);
Shorter and better version of above code
Updated fiddle Demo
var left = $('#left'),
right = $('#right'),
arr = [];
var x = $('#main .dataCard').sort(function (a, b) {
return $(a).data('cardnumber') - $(b).data('cardnumber');
});
arr = $.makeArray(x);
left.html(arr.slice(0, left.children().length));
right.html(arr.slice(left.children().length));
While iterating through your .dataCard's you can do something like this to check the height and append the .dataCard accordingly.
var x = $('#main .dataCard').sort(function (a, b) {
return $(a).data('cardnumber') - $(b).data('cardnumber');
});
for(var i = 0; i < x.length;i++){
if($('#left').height() <= $('#right').height()){
$('#left').append(x[i]);
}
else
$('#right').append(x[i]);
});
http://jsfiddle.net/trevordowdle/p9q6h/2/
just check for the height of left and right everytime and compare.
var toAppend,
$left = $("#left"),
$right = $("#right");
$left.height() > $right.height() ? toAppend = $right : toAppend = $left;
Use the toAppend variable now.

Categories

Resources