designerNProgrammer
designerNProgrammer

Reputation: 2701

How to do this specific task by a function using jQuery?

I am working on this vertical scrolling gallery. Now I cannot work it out but I need to make this code less verbose. the code I've been writing is to repetative. this is the code

var target1 = $("#myImg1").offset().top;
var target2 = $("#myImg2").offset().top;

if ($(window).scrollTop() >= target1 - 150 
 && $(window).scrollTop() <= target1 + 150) {
    showBgOnTop('#firstImage','#secondImage');  
}
if ($(window).scrollTop() >= target2 - 150 
 && $(window).scrollTop() <= target2 + 150) {
    showBgOnTop('#secondImage','#firstImage');
}

Can I use some kind of function here to shorten the code. Like an array.
please tell me what i am doing wrong here. thanks.

Upvotes: 0

Views: 64

Answers (3)

oldhomemovie
oldhomemovie

Reputation: 15129

How about this:

function show(image1id, image2id) {
  var target1 = $(image1id).offset().top;
  var target2 = $(image2id).offset().top;

  if (($(window).scrollTop() >= target2 - 150) &&
       $(window).scrollTop() <= target2 + 150)) {
    showBgOnTop(image1id, image2id);
  }
}

show('#firstImage','#secondImage');
show('#secondImage','#firstImage');

Upvotes: 0

dcodesmith
dcodesmith

Reputation: 9614

Explanation

It seems like you have a jQuery object as your target that's linked to two images and you'd like to have multiple instances of this, say at least 2.

So my solution is to have an array of objects with this format

var array = [
    {target: ['image1', 'image2']}
]

target being the target element id and the value being an array of the ids of the associated images.

Now all the user has to do is keep on adding new objects to the array in the format shown above.

Solution

// Put the target object id as keys and the array of the linked/associated elements as values
var arrs = [
        {'#myImg1': ['#firstImage', '#secondImage']},
        {'#myImg2': ['#secondImage', '#firstImage']},
        {'#myImg3': ['...', '...']} // keep adding new items as object here
    ],
    $windowScrollTop = $(window).scrollTop(); // cache window scroll function

// loop through the array here
$.each(arrs, function (idx, obj) { 
    for (id in obj) {
        var $el = $(id), // cache the target element here
            args = obj[id],
            img1 = args[0].toString(),
            img2 = args[1].toString();

        if ($windowScrollTop >= $el - 150 && $windowScrollTop <= $el + 150) {
            showBgOnTop(img1, img2);
        }

    }

});

Upvotes: 1

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

Well, this actually is a jQuery function.

The only thing you can do to lessen the code is to use

$(window).scrollTop()

as a variable:

var windowScrollTop = $(window).scrollTop();

Remaining part is a condition, you cannot use conditions are variables.

Upvotes: 0

Related Questions