Joel
Joel

Reputation: 456

Trying to loop a function to run on multiple elements - jQuery

I'm trying to get this jQuery parallax code to work but I don't want to spaghetti everything. How can it be looped to apply to multiple element IDs?

(it doesn't work with classes because the function needs to run multiple times specific to each particular div) - I'm not very good when it comes to looping, still learning how to do this stuff.

Anyway, this is a functioning code for one section (a div with a child div, #about > #pAbout in this instance):

$(document).ready(function() {
  if ($("#pAbout").length) {
    parallax();
  }
});

$(window).scroll(function(e) {
  if ($("#pAbout").length) {
    parallax();
  }
});

function parallax(){
  if( $("#pAbout").length > 0 ) {
    var plxBackground = $("#pAbout");
    var plxWindow = $("#about");

    var plxWindowTopToPageTop = $(plxWindow).offset().top;
    var windowTopToPageTop = $(window).scrollTop();
    var plxWindowTopToWindowTop = plxWindowTopToPageTop - windowTopToPageTop;

    var plxBackgroundTopToPageTop = $(plxBackground).offset().top;
    var windowInnerHeight = window.innerHeight;
    var plxBackgroundTopToWindowTop = plxBackgroundTopToPageTop - windowTopToPageTop;
    var plxBackgroundTopToWindowBottom = windowInnerHeight - plxBackgroundTopToWindowTop;
    var plxSpeed = 0.35;

    plxBackground.css('top', - (plxWindowTopToWindowTop * plxSpeed) + 'px');
  }
}

I was hoping to create an array like this:

var ids = ['#pAbout', '#pConcept', '#pBroadcast', '#pDigital', '#pDesign', '#pContact'];

But I can't get the e business to work unfortunately, it's very frustrating for me. Any help would be greatly appreciated!

Upvotes: 2

Views: 1064

Answers (1)

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

You can use multiple selector in jQuery to select disparate elements by simply using a comma between the selectors.

 $("#pAbout, #pConcept, #pBroadcast, #pDigital, #pDesign, #pContact")
    .each(function(){
     //manipulate element here
 });

That each() iterates over all matched elements so no need to check for length etc.

Upvotes: 1

Related Questions