Call a function using $('.class').each(functionName); - javascript

I have a codepen here -
http://codepen.io/ashconnolly/pen/EjMbQp
function homepanelHeights() {
$('.img_panel').each(function() {
if (currentWidth < 700) {
var panelcopyHeight = $(this).find('.panel_copy_inner').outerHeight();
console.log(panelcopyHeight);
$(this).css('height', panelcopyHeight);
} else {
// remove inline style
$(this).css("height", "");
}
});
}
$(document).ready(function() {
$('.img_panel').each(homepanelHeights);
});
$(window).resize(function() {
$('.img_panel').each(homepanelHeights);
});
I want to apply a function to each element with .img_panel.
Do you know why the each function call is not working?
I assume its because of the arguments I'm passing, but can not work it out.
it works if I simply repeat the function in the doc.ready and window.resize, but that is a bit dirty..
Hope you can help!

You just need to call homepanelHeights(); Because when you using $('.img_panel').each(...) in homepanelHeights, you're already iterating through it, $('.img_panel').each(homepanelHeights);, combine with the logic inside the function, can be considered as:
// This is the outer
$('.img_panel').each(function() {
// This is inside your homepanelHeights
$('.img_panel').each(function() {
// Do something.
});
});
So you can see that that the logic n*n times.
currentWidth is undefined in your codepen. Added a fake to show.
function homepanelHeights(){
$('.img_panel').each(function (){
// VVVV Make the `currentWidth` get value here, it needs the current width
// when window content is fully loaded, or resized.
var currentWidth = $(window).width();
if (currentWidth < 700){
var panelcopyHeight = $(this).find('.panel_copy_inner').outerHeight();
console.log(panelcopyHeight);
$(this).css('height', panelcopyHeight);
} else {
// remove inline style
$(this).css("height", "");
}
});
}
// As A. Wolff said :
// $(window).on('load resize', homepanelHeights); Can simplify the code.
$(document).ready(function() {
homepanelHeights();
});
$(window).resize(function() {
homepanelHeights();
});
.img_panel {background:salmon; width:200px; height:300px; margin-bottom:10px; display:table;
.panel_copy_inner {height:100%; display: table-cell; vertical-align:middle; text-align: center;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="img_panel">
<div class="panel_copy_inner">Test</div>
</div>
<div class="img_panel">
<div class="panel_copy_inner">Test</div>
</div>
<div class="img_panel">
<div class="panel_copy_inner">Test</div>
</div>
If you want to use the function homepanelHeights as $('.img_panel').each(homepanelHeights);
You can rewrite the logic to:
var currentWidth;
// You need to either define a `currentWidth` here by something.
function homepanelHeights(){
if (currentWidth < 700){
var panelcopyHeight = $(this).find('.panel_copy_inner').outerHeight();
console.log(panelcopyHeight);
$(this).css('height', panelcopyHeight);
} else {
// remove inline style
$(this).css("height", "");
}
}
// As A. Wolff said :
$(window).on('load resize', function() {
// Update the width here. So you don't need to get currentWidth
// each time you operate on an element.
currentWidth = $(window).width();
$('.img_panel').each(homepanelHeights);
});
Demo is on jsfiddle.

Here i have modified the code to achieve the functionality for each element.
Please see the code below.
homepanelHeights=function(key, val) {
var currentWidth = $(window).width();
console.log(currentWidth);
if (currentWidth < 700) {
var panelcopyHeight = $(this).find('.panel_copy_inner').outerHeight();
//console.log(panelcopyHeight);
$(this).css('height', panelcopyHeight);
} else {
// remove inline style
$(this).css("height", "");
}
}
/**/
$(document).ready(function() {
$('.img_panel').each(homepanelHeights);
});
$(window).resize(function() {
$('.img_panel').each(homepanelHeights);
});

function homepanelHeights(){
//This will iterate through all element having img_panel class
$('.img_panel').each(function(){
//get current div's height
var currentWidth = //assign some value here, it is undefined in your current code;
// your logic implemetation
if (currentWidth < 700)
{
var panelcopyHeight = $(this).find('.panel_copy_inner').outerHeight();
console.log(panelcopyHeight);
$(this).css('height', panelcopyHeight);
}
else {
$(this).css("height", "");
}
})
}
// on window load && resize
$(window).on('load resize',function() {
homepanelHeights();
});
//Or instead of window on load you can also use document's ready event
$(document).ready(function() {
homepanelHeights();
});
document.ready runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all the content.
window.onload fires later (or at the same time in the worst/failing cases) when images and such are loaded. So, if you're using image dimensions for example, you often want to use this instead

Related

Why doesn this JQuery resize work?

I am trying to get a script to run only if the viewport is below 1025. Then on resize, if if the screen size is increased either ignore or run the script. At present it runs whatever screen size.
$(document).ready(function() {
$(window).resize(function() {
if ($(window).width() < 1025) {
var $caseStudies = $('.case-study');
$('.pagination div').on('click', function() {
$caseStudies.css("position", "absolute");
$caseStudies.eq($(this).index()).css("position", "relative");
});
}
else {
// ELEMENT IS ABSOLUTE
}
});
});
There's nothing in your code to remove the handler you set up in the < 1025 case when the window is no longer < 1025 in size. You have to explicitly remove the handler. Probably the easiest way is with an event class. You'll also need a marker to indicate whether the handler has been attached. See *** comments:
$(document).ready(function() {
var hasHandler = false;
$(window).resize(function() {
if ($(window).width() < 1025) {
// *** Add handler if we don't already have it
if (!hasHandler) {
hasHandler = true;
var $caseStudies = $('.case-study');
$('.pagination div').on('click.positioner', function() {
// *** Note ------------------^^^^^^^^^^^
$caseStudies.css("position", "absolute");
$caseStudies.eq($(this).index()).css("position", "relative");
});
}
}
else {
// If we ever added a handler...
if (hasHandler) {
hasHandler = false;
// *** Remove it
$('.pagination div').off('click.positioner');
// *** Make them all relative again
$('.case-study').css("position", "relative");
}
}
});
});
In a comment you've said:
... this script only seems to work after I resize the browser. I would need it to work if the browser was less than 1025 but detect a resize, if resized
Then you'd simply put the code in a function and call that function both from ready (on page load) and in response to resize:
$(document).ready(function() {
var hasHandler = false;
function handlePositioning() {
if ($(window).width() < 1025) {
// *** Add handler if we don't already have it
if (!hasHandler) {
hasHandler = true;
var $caseStudies = $('.case-study');
$('.pagination div').on('click.positioner', function() {
// *** Note ------------------^^^^^^^^^^^
$caseStudies.css("position", "absolute");
$caseStudies.eq($(this).index()).css("position", "relative");
});
}
}
else {
// If we ever added a handler...
if (hasHandler) {
hasHandler = false;
// *** Remove it
$('.pagination div').off('click.positioner');
// *** Make them all relative again
$('.case-study').css("position", "relative");
}
}
}
handlePositioning();
$(window).resize(handlePositioning);
});
(Or you can add .trigger("resize") at the end of the .on call in the first code block above to trigger the event after adding it, but that's always seemed hacky to me...)

JQuery function with media width

I created a JQuery script, which fade in a sidebar, when scrolling down for 500px. This is working without any errors. However, I tried to wrap it in another function, which checks the media size. The fade in should only work, if the media size is greater than 1024. It does not work and I don't get any error in the console. Can you pls help me?
jQuery(function($) {
function checkPosition() {
if (window.matchMedia('(min-width: 767px)').matches) {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$("body").addClass("right_side_menu_opened");
$(".side_menu").addClass("nav-fade");
}
else {
$("body").removeClass("right_side_menu_opened");
$(".side_menu").removeClass("nav-fade");
}
});
} else {
}
}
});
You have wrapped the whole JS inside a function which never gets called.
You should
remove the function declaration (function checkPosition())
or call the function (checkPosition())
Removing the declaration:
jQuery(function($) {
if (window.matchMedia('(min-width: 767px)').matches) {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$("body").addClass("right_side_menu_opened");
$(".side_menu").addClass("nav-fade");
}
else {
$("body").removeClass("right_side_menu_opened");
$(".side_menu").removeClass("nav-fade");
}
});
} else {
}
});
Calling the function:
jQuery(function($) {
function checkPosition() {
if (window.matchMedia('(min-width: 767px)').matches) {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$("body").addClass("right_side_menu_opened");
$(".side_menu").addClass("nav-fade");
}
else {
$("body").removeClass("right_side_menu_opened");
$(".side_menu").removeClass("nav-fade");
}
});
} else {
}
}
checkPosition();
});
Note: if you want to check viewport size, you could use $(window).width(); to get the width of viewport.

Use function as an "on" event?

I currently have this function:
function highlightBoxes() {
var windowStart = $(window).scrollTop();
var windowEnd = windowStart + $(window).height();
$('.box').each(function() {
var box = $(this);
var start = box.offset().top;
var end = start + box.height();
if (windowStart <= start && windowEnd >= end) {
box.addClass('active');
} else {
box.removeClass('active');
}
});
}
highlightBoxes();
$(document).scroll(highlightBoxes);
$(window).resize(highlightBoxes);
Which checks if an entire element (in this case .box) is in view (jsfiddle). However, I want to be able to use the function as an on event, so I can use it for many different elements. Something like:
$('.box').on('inview', function () {
if (elementIsInView) {
// make the box red
} else {
// make the box the original color
}
});
How can I do this?
using on means you will need to trigger an event with the same name, a super simple version of this is using document as the message bus like:
$(document).trigger('inview');
Therefore at the point in your code where you have decided that inview should be true, fire an event like the above, at which point the on event will run the function.
Base on the code above, you probably want to move the if statement out of the on event, and in fact run that as a separate function. When elementIsInView returns true, you could fire the inview event.
You could use the hover event.
$(document).on('hover','.box', function () {
if (elementIsInView) {
// make the box red
} else {
// make the box the original color
}
});
If am not clear with your answer let me know.
click ,hover ,drag all are events. Event is a action, apply from user. Function is a declare with javascript.Is not directly running.Its only run after event trigger.Event are declared by w3c
I think you need something like that:
Assign function with button click.Its works from button click event.
$('button').on('click',hello)
function hello(){
console.log('button Clicked')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button >hi</button>
or
$('button').on('click',function hello(){
console.log('button Clicked')
})
For your code do like this
$('.box').on('click', function inview() {
if (elementIsInView) {
// make the box red
} else {
// make the box the original color
}
});
try this:
function checkElementToBeInView(elem, callback) {
$(elem).each(function() {
var element = $(this);
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = element.offset().top;
var elemBottom = elemTop + element.height();
var isInView = ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
callback(element, isInView);
});
}
$(window).on("load resize scroll", function(e) {
checkElementToBeInView(".box", function(elem, isInView) {
if (isInView)
elem.addClass('active');
else
elem.removeClass('active');
});

Changing text content on scroll position

I found a solution that didn't work mainly that I want. Here it is:
topic url
and this solution works for me:
if(pos.top >= $(this).offset().top && pos.top <= $(this).next().offset().top)
{
$('#date').html($(this).find('.description').text());
return;
}
jsfiddle
but I want to change content description in gray box more smooth. I've tried to give animation in CSS for it, but it didn't work.
I modified your script a bit to detect when the text changes and when that happens I apply a small animation with jQuery. I set the opacity to a low value, e.g. opacity:0.4 and then make a quick animation back to opacity:1.
This will help your user to see easier the change in the text.
$(window).load(function () {
$(window).on('scroll resize', function () {
var pos = $('#date').offset();
$('.post').each(function () {
if (pos.top >= $(this).offset().top && pos.top <= $(this).next().offset().top) {
var newDescr = $(this).find('.description').text();
var oldDescr = $('#date').html();
$('#date').html(newDescr);
if(newDescr !== oldDescr) {
$('#date').css('opacity', 0.4).animate({ 'opacity': '1',}, 200);
return;
}
}
});
});
$(document).ready(function () {
$(window).trigger('scroll'); // init the value
});
});
Demo here

$(window).resize() doesn't fire function

I wrote a function that's supposed to fire when the page first loads, and when a user resizes the window. It works fine when the page loads, but it doesn't work when the user resizes the window. What's weird is that if I put an alert inside the function, that alert shows up when the window gets resized, but the rest of the function doesn't fire. I'm not seeing any error's in Chrome's console. I've tried changing it to $(document).resize(), $("body").resize(), and $(".pricingHeader").resize(), and nothing's worked. This makes no sense to me.
function getTallest() {
var tallest = 0;
$(".pricingHeader").not(".features .pricingHeader").each(function(){
tallest = $(this).height() > tallest?$(this).height():tallest;
});
$(".pricingHeader").not(".features .pricingHeader").height(tallest);
$(".features .pricingHeader").height(tallest + 8);
}
$(document).ready(function() {
getTallest();
});
$(window).resize(function() {
getTallest();
});
Try :
function getTallest() {
var tallest = 0;
$(".pricingHeader").not(".features .pricingHeader").each(function(i, elem){
if ( $(elem).height() > tallest ) tallest = $(elem).height();
});
$(".pricingHeader").height(function() {
var add = $(this).closest('.features').length ? 8 : 0;
return tallest+add;
});
}
$(function() {
$(window).on('resize', getTallest).trigger('resize');
});
Alright, I figured out what the problem was. I was setting the height of every .pricingHeader to a fixed height, which was preventing the tallest from resizing on window resize. Here's the fixed script:
function getTallest() {
var tallest = 0;
$(".pricingHeader").not(".features .pricingHeader").each(function(){
$(this).css({height:"auto"});
tallest = $(this).height() > tallest?$(this).height():tallest;
});
$(".pricingHeader").each(function() {
$(".pricingHeader").not(".features .pricingHeader").height(tallest);
$(".features .pricingHeader").height(tallest + 8);
});
}
$(document).ready(function() {
getTallest();
});
$(window).resize(function() {
getTallest();
});

Categories

Resources