2

I have this code:

    $(window).scroll(function(){
        $('#globalnav').css('left',-$(window).scrollLeft());
        $('#globalborder').css('left',-$(window).scrollLeft());
        $('#backgroundlayer').css('left',-$(window).scrollLeft());
    });

How can I make al the variables compiled in just one line? So it should like something like this

    $(window).scroll(function(){
        $('#globalnav','#globalborder','#backgroundlayer').css('left',-$(window).scrollLeft());
    });
5
  • Note that by keeping the , outside of the ', you are passing multiple arguments to the jQuery $ function. Using adeneo's answer, you are passing a single argument to $, which is a string representing a list of selectors.
    – ajp15243
    Commented Apr 15, 2014 at 18:33
  • possible duplicate of jQuery Multiple ID selectors Commented Apr 15, 2014 at 18:34
  • 1
    @epascarello That looks like an issue with whatever upload plugin that questioner was using, rather than an issue selecting multiple items by id, despite the title.
    – ajp15243
    Commented Apr 15, 2014 at 18:36
  • Than pick: stackoverflow.com/questions/488305/… There are 100s of related ones. Commented Apr 15, 2014 at 18:44
  • @epascarello I didn't say there weren't other related ones, and I'm certainly not stopping you from marking this as a duplicate.
    – ajp15243
    Commented Apr 15, 2014 at 18:45

1 Answer 1

9

Just drop some quotes

$(window).scroll(function(){
    $('#globalnav, #globalborder, #backgroundlayer').css('left',-$(window).scrollLeft());
});

If you pass the elements as a comma separated list in one single string to the selector, they are all added.

If you use a comma separated list of different strings, you're using the "context selector", which is a shortcut for find() and works differently.

8
  • if we pass one selector in single quotes then comma as OP was doing what will happen actually Commented Apr 15, 2014 at 18:35
  • @EhsanSajjad you can set up a fiddle that will allow you to test what happens with different selectors. Commented Apr 15, 2014 at 18:38
  • Is it also possible to delete the # and say that that should al have that before? Commented Apr 15, 2014 at 18:38
  • @EhsanSajjad The $/jQuery function will attempt to match the arguments following one of its signatures, as seen in the API docs. However, none of its signatures takes 3 arguments, and as some quick console testing via dev tools revealed on the jQuery website, an empty jQuery object is returned. Presumably, this is the default behavior if it cannot match arguments to one of its signatures.
    – ajp15243
    Commented Apr 15, 2014 at 18:38
  • The context selector calls find internally, so this $('.child', '#parent') is equal to $('#parent').find('.child'), of course trying to call that with three arguments fails.
    – adeneo
    Commented Apr 15, 2014 at 18:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.