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

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

Related

How can I use constructor to write this code?

This is about ellipsis in multiple text in responsive design.
I use jQuery to do it, but I think it will be more easier to write this code, but I have no idea to do it. I need some advice.
if(responsive>1200 && responsive<1919){
$(".ellipsis-2").each(function(){
var maxwidth=15;
if($(this).text().length > maxwidth){
$(this).text($(this).text().substring(0,maxwidth));
$(this).html($(this).html()+'...');
}
console.log($(this).text().length);
});
$(".ellipsis-3").each(function(){
var maxwidth=40;
if($(this).text().length > maxwidth){
$(this).text($(this).text().substring(0,maxwidth));
$(this).html($(this).html()+'...');
}
console.log($(this).text().length);
});
}else{
$(".ellipsis-2").each(function(){
var maxwidth=23;
if($(this).text().length > maxwidth){
$(this).text($(this).text().substring(0,maxwidth));
$(this).html($(this).html()+'...');
}
console.log($(this).text().length);
});
$(".ellipsis-3").each(function(){
var maxwidth=53;
if($(this).text().length > maxwidth){
$(this).text($(this).text().substring(0,maxwidth));
$(this).html($(this).html()+'...');
}
console.log($(this).text().length);
});
}
You just need a function to simplify your code, not really a constructor. Create one for the ellipsis logic receiving the selector for the elements to be applied as well as the max width:
function applyEllipsis(selector, maxWidth){
$(selector).each(function(){
if($(this).text().length > maxWidth){
$(this).text($(this).text().substring(0,maxWidth));
$(this).html($(this).html()+'...');
}
console.log($(this).text().length);
});
}
Now you can call it inside your if statements passing the selector and max width that you need for each case:
if(responsive>1200 && responsive<1919){
applyEllipsis(".ellipsis-2",15);
applyEllipsis(".ellipsis-3",40);
}else{
applyEllipsis(".ellipsis-2",23);
applyEllipsis(".ellipsis-3",53);
}
Depending on what else is after this code you might find some use in storing your class/width values in an object array:
var ellipsisData = [
{
className: 'ellipses-2',
smallWidth: 15,
bigWidth: 23
},{
className: 'ellipses-3',
smallWidth: 23,
bigWidth: 53
}
]
Then declare your function like the other answer:
var truncateText = function(className, maxWidth) {
$("." + className).each(function() {
if($(this).text().length > maxWidth) {
$(this).text($(this).text().substring(0,maxWidth));
$(this).html($(this).html()+'...');
}
console.log($(this).text().length);
});
};
Now decide which width you want to use:
var widthKey = (responsive > 1200 && responsive < 1919) ? 'smallWidth' : 'bigWidth';
And finally iterate over your data elements and perform the function on each:
ellipsisData.forEach(function(ellipsis) {
truncateText(ellipsis.className, ellipsis[widthKey]);
});
Unnecessary probably, but I'd already written it up so I figured I'd post it.

Improve script of setting height of div by comparing two heights

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

Get static value from variable (scroll function)

I have a "follow scroll" function, but I want it to turn off when it returns to a certain point. My code is as follows:
scrollSidebar: function(scroll) {
var elemPos = $('#bestvideos-2').offset().top,
scroll2 = scroll;
if(scroll2 >= elemPos) {
$('#bestvideos-2').animate({
'margin-top':(scroll - 315)+'px'
},0);
} else {
$('#bestvideos-2').css('margin-top','0');
}
}
$(window).scroll(function() {
var scrollHeight = $(window).scrollTop();
Scroll.scrollSidebar(scrollHeight);
})
The problem is - every time I get up, it goes way up, not following scroll. What I'm thinking is storing a variable elemPos somewhere and keep it static (now it's changing each time I scroll).
What can I do with this?
Pass the value to the scrollSidebar function - make sure that the var elemPos = $('#bestvideos-2').offset().top is executed on dom ready
scrollSidebar: function (elemPos, scroll) {
var scroll2 = scroll;
if (scroll2 >= elemPos) {
$('#bestvideos-2').animate({
'margin-top': (scroll - 315) + 'px'
}, 0);
} else {
$('#bestvideos-2').css('margin-top', '0');
}
}
var elemPos = $('#bestvideos-2').offset().top
$(window).scroll(function () {
var scrollHeight = $(window).scrollTop();
Scroll.scrollSidebar(elemPos, scrollHeight);
})

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

How to check if a DIV is scrolled all the way to the bottom with jQuery

I have a div with overflow:scroll.
I want to know if it's currently scrolled all the way down. How, using JQuery?
This one doesn't work: How can I determine if a div is scrolled to the bottom?
Here is the correct solution (jsfiddle). A brief look at the code:
$(document).ready(function () {
$('div').on('scroll', chk_scroll);
});
function chk_scroll(e) {
var elem = $(e.currentTarget);
if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) {
console.log("bottom");
}
}
See this for more info.
function isScrolledToBottom(el) {
var $el = $(el);
return el.scrollHeight - $el.scrollTop() - $el.outerHeight() < 1;
}
This is variation of #samccone's answer that incorporates #HenrikChristensen's comment regarding subpixel measurements.
Since it works without jQuery like that :
var isBottom = node.scrollTop + node.offsetHeight === node.scrollHeight;
I do :
var node = $('#mydiv')[0]; // gets the html element
if(node) {
var isBottom = node.scrollTop + node.offsetHeight === node.scrollHeight;
}
You can do that by
(scrollHeight - scrollTop()) == outerHeight()
Apply required jQuery syntax, of course...
Here is the code:
$("#div_Id").scroll(function (e) {
e.preventDefault();
var elem = $(this);
if (elem.scrollTop() > 0 &&
(elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight())) {
alert("At the bottom");
}
});
Since 2012 Firefox contains the scrollTopMax property. If scrollTop === scrollTopMax you're at the bottom of the element.
Without jquery, for onScroll event
var scrollDiv = event.srcElement.body
window.innerHeight + scrollDiv.scrollTop == scrollDiv.scrollHeight
For me $el.outerHeight() gives the wrong value (due to the border width), whereas $el.innerHeight() gives the correct one, so I use
function isAtBottom($el){
return ($el[0].scrollHeight - $el.scrollTop()) == $el.innerHeight();
}

Categories