jQuery: The Write Less, Do More JavaScript Library

JQuery events and a possible scoping error on my part?

View: New views
10 Messages — Rating Filter:   Alert me  

JQuery events and a possible scoping error on my part?

by bsenftner :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Just learning Java Script & JQuery, but an experienced developer, I've created a page with a series of elements that use the .slideDown() and .slideUp() functions to reveal and hide the different areas of content on the page.

To facilitate this, the page's html uses links with ids similar to: { "dataRevealLink1", "dataToReveal1", "dataHideLink1" }. Clicking on a "data-reveal-link" causes a .slideDown() animation on "data to reveal", with appropriate reverse logic attached for the data hiding as well.

The page in question has 12 such sections, and writing the script long form (no loops) works fine. However, I would like to generalize this logic, but my first attempt at a loop to attach the DOM element callbacks does not work, and I suspect it's a scoping issue with java script:

for (var i = 1; i <= 12; i++) {
var eventElem = "#dataRevealLink" + i;
var actOnElem = "#dataToReveal" + i;

$(eventElem).click( function() {
   $(actOnElem).slideDown();
   return false; // prevents the link from processing this click
  });
}

I suspect that in the above logic, the mouse-click callback is attaching to the dataRevealLink1-12 fine, however once inside the callback, "actOnElem" is not what I'm expecting - possibly due to the scope of actOnElem? I'm not entirely sure...

I've added console.log() calls to the above logic, and everything is as I expect during the above looping, but I am never getting any of the callbacks to run, so I can never see any console.log() output from inside a mouse-click handler...

Any advice anyone?


Re: JQuery events and a possible scoping error on my part?

by north-6 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


Hi,

I'm not a JS/jQuery expert, so as a quick test I added alert
(actOnElem); inside your $(eventElem).click( function(), and the
result always was #dataToReveal12.

As mentioned, I am not an expert and still learning myself, but I
think on dom ready the loop simply starts running until i equals 12.
And it's not until then, that the click function comes into play.
That's all I can say at the moment. If I have more time later, I will
look into this again.

Cheers


On 4 Jul., 03:59, bsenftner <bsenft...@...> wrote:

> Just learning Java Script & JQuery, but an experienced developer, I've
> created a page with a series of elements that use the .slideDown() and
> .slideUp() functions to reveal and hide the different areas of content on
> the page.
>
> To facilitate this, the page's html uses links with ids similar to: {
> "dataRevealLink1", "dataToReveal1", "dataHideLink1" }. Clicking on a
> "data-reveal-link" causes a .slideDown() animation on "data to reveal", with
> appropriate reverse logic attached for the data hiding as well.
>
> The page in question has 12 such sections, and writing the script long form
> (no loops) works fine. However, I would like to generalize this logic, but
> my first attempt at a loop to attach the DOM element callbacks does not
> work, and I suspect it's a scoping issue with java script:
>
>      for (var i = 1; i <= 12; i++) {
>          var eventElem = "#dataRevealLink" + i;
>          var actOnElem = "#dataToReveal" + i;
>
>          $(eventElem).click( function() {
>                               $(actOnElem).slideDown();
>                               return false;           // prevents
> the link from processing this click
>            });
>      }
>
> I suspect that in the above logic, the mouse-click callback is attaching to
> the dataRevealLink1-12 fine, however once inside the callback, "actOnElem"
> is not what I'm expecting - possibly due to the scope of actOnElem? I'm not
> entirely sure...
>
> I've added console.log() calls to the above logic, and everything is as I
> expect during the above looping, but I am never getting any of the callbacks
> to run, so I can never see any console.log() output from inside a
> mouse-click handler...
>
> Any advice anyone?
>
> --
> View this message in context:http://www.nabble.com/JQuery-events-and-a-possible-scoping-error-on-m...
> Sent from the jQuery General Discussion mailing list archive at Nabble.com.

Re: JQuery events and a possible scoping error on my part?

by north-6 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


OK, I guess this is one possible solution:

$('a[id^=dataRevealLink]').each(function(){
                var eventElemId = $(this).attr('id');
                var eventElemIdNo = eventElemId.substring(14, eventElemId.length);
                var actOnElem = $('#dataToReveal' +eventElemIdNo);
                $(this).click(function() {
                        actOnElem.slideDown();
                        return false;
                })
});

Cheers

On 4 Jul., 12:59, olsch01 <ollo...@...> wrote:

> Hi,
>
> I'm not a JS/jQuery expert, so as a quick test I added alert
> (actOnElem); inside your $(eventElem).click( function(), and the
> result always was #dataToReveal12.
>
> As mentioned, I am not an expert and still learning myself, but I
> think on dom ready the loop simply starts running until i equals 12.
> And it's not until then, that the click function comes into play.
> That's all I can say at the moment. If I have more time later, I will
> look into this again.
>
> Cheers
>
> On 4 Jul., 03:59, bsenftner <bsenft...@...> wrote:
>
> > Just learning Java Script & JQuery, but an experienced developer, I've
> > created a page with a series of elements that use the .slideDown() and
> > .slideUp() functions to reveal and hide the different areas of content on
> > the page.
>
> > To facilitate this, the page's html uses links with ids similar to: {
> > "dataRevealLink1", "dataToReveal1", "dataHideLink1" }. Clicking on a
> > "data-reveal-link" causes a .slideDown() animation on "data to reveal", with
> > appropriate reverse logic attached for the data hiding as well.
>
> > The page in question has 12 such sections, and writing the script long form
> > (no loops) works fine. However, I would like to generalize this logic, but
> > my first attempt at a loop to attach the DOM element callbacks does not
> > work, and I suspect it's a scoping issue with java script:
>
> >      for (var i = 1; i <= 12; i++) {
> >          var eventElem = "#dataRevealLink" + i;
> >          var actOnElem = "#dataToReveal" + i;
>
> >          $(eventElem).click( function() {
> >                               $(actOnElem).slideDown();
> >                               return false;           // prevents
> > the link from processing this click
> >            });
> >      }
>
> > I suspect that in the above logic, the mouse-click callback is attaching to
> > the dataRevealLink1-12 fine, however once inside the callback, "actOnElem"
> > is not what I'm expecting - possibly due to the scope of actOnElem? I'm not
> > entirely sure...
>
> > I've added console.log() calls to the above logic, and everything is as I
> > expect during the above looping, but I am never getting any of the callbacks
> > to run, so I can never see any console.log() output from inside a
> > mouse-click handler...
>
> > Any advice anyone?
>
> > --
> > View this message in context:http://www.nabble.com/JQuery-events-and-a-possible-scoping-error-on-m...
> > Sent from the jQuery General Discussion mailing list archive at Nabble.com.

Re: JQuery events and a possible scoping error on my part?

by Charlie Tomlinson :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Cleaner if you can use a class on the links. Assume they now have class "dataReveal".

i=1;
$(".dataReveal").each(function () {
        var actOnElem = "#dataToReveal" +i;
           $(this).click( function() {         
           $(actOnElem).slideDown();          
            return false; 
         });
         i++;
     });




olsch01 wrote:
OK, I guess this is one possible solution:

$('a[id^=dataRevealLink]').each(function(){
		var eventElemId = $(this).attr('id');
		var eventElemIdNo = eventElemId.substring(14, eventElemId.length);
		var actOnElem = $('#dataToReveal' +eventElemIdNo);
		$(this).click(function() {
			actOnElem.slideDown();
			return false;
		})
});

Cheers

On 4 Jul., 12:59, olsch01 ollo...@... wrote:
  
Hi,

I'm not a JS/jQuery expert, so as a quick test I added alert
(actOnElem); inside your $(eventElem).click( function(), and the
result always was #dataToReveal12.

As mentioned, I am not an expert and still learning myself, but I
think on dom ready the loop simply starts running until i equals 12.
And it's not until then, that the click function comes into play.
That's all I can say at the moment. If I have more time later, I will
look into this again.

Cheers

On 4 Jul., 03:59, bsenftner bsenft...@... wrote:

    
Just learning Java Script & JQuery, but an experienced developer, I've
created a page with a series of elements that use the .slideDown() and
.slideUp() functions to reveal and hide the different areas of content on
the page.
      
To facilitate this, the page's html uses links with ids similar to: {
"dataRevealLink1", "dataToReveal1", "dataHideLink1" }. Clicking on a
"data-reveal-link" causes a .slideDown() animation on "data to reveal", with
appropriate reverse logic attached for the data hiding as well.
      
The page in question has 12 such sections, and writing the script long form
(no loops) works fine. However, I would like to generalize this logic, but
my first attempt at a loop to attach the DOM element callbacks does not
work, and I suspect it's a scoping issue with java script:
      
     for (var i = 1; i <= 12; i++) {
         var eventElem = "#dataRevealLink" + i;
         var actOnElem = "#dataToReveal" + i;
      
         $(eventElem).click( function() {
         &nbsp&nbsp                   $(actOnElem).slideDown();
         &nbsp&nbsp                   return false;           // prevents
the link from processing this click
         &nbsp&nbsp});
     }
      
I suspect that in the above logic, the mouse-click callback is attaching to
the dataRevealLink1-12 fine, however once inside the callback, "actOnElem"
is not what I'm expecting - possibly due to the scope of actOnElem? I'm not
entirely sure...
      
I've added console.log() calls to the above logic, and everything is as I
expect during the above looping, but I am never getting any of the callbacks
to run, so I can never see any console.log() output from inside a
mouse-click handler...
      
Any advice anyone?
      
--
View this message in context:http://www.nabble.com/JQuery-events-and-a-possible-scoping-error-on-m...
Sent from the jQuery General Discussion mailing list archive at Nabble.com.
      

  


Re: JQuery events and a possible scoping error on my part?

by north-6 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


Hi Charlie,

one drawback of your function that I see is, that it only works if the
divs with the data to reveal appear in sorted order in the code (i.e.
dataToReveal1, dataToReveal2, dataToReveal3 etc.). If you mix them up,
the function doesn't work properly anymore (at least not in my test),
since your just counting up i. So there is only a loose connection
between the link and the data div.

Doesn't necessarily have to been an issue though :)


On 4 Jul., 16:17, Charlie <charlie...@...> wrote:

> Cleaner if you can use a class on the links. Assume they now have class "dataReveal".
> i=1;
> $(".dataReveal").each(function () {
>         var actOnElem = "#dataToReveal" +i;
>            $(this).click( function() {         
>            $(actOnElem).slideDown();          
>             return false; 
>          });
>          i++;
>      });
> olsch01 wrote:OK, I guess this is one possible solution: $('a[id^=dataRevealLink]').each(function(){ var eventElemId = $(this).attr('id'); var eventElemIdNo = eventElemId.substring(14, eventElemId.length); var actOnElem = $('#dataToReveal' +eventElemIdNo); $(this).click(function() { actOnElem.slideDown(); return false; }) }); Cheers On 4 Jul., 12:59, olsch01<ollo...@...>wrote:Hi, I'm not a JS/jQuery expert, so as a quick test I added alert (actOnElem); inside your $(eventElem).click( function(), and the result always was #dataToReveal12. As mentioned, I am not an expert and still learning myself, but I think on dom ready the loop simply starts running until i equals 12. And it's not until then, that the click function comes into play. That's all I can say at the moment. If I have more time later, I will look into this again. Cheers On 4 Jul., 03:59, bsenftner<bsenft...@...>wrote:Just learning Java Script & JQuery, but an experienced developer, I've created a page with a series of elements that use the .slideDown() and .slideUp() functions to reveal and hide the different areas of content on the page.To facilitate this, the page's html uses links with ids similar to: { "dataRevealLink1", "dataToReveal1", "dataHideLink1" }. Clicking on a "data-reveal-link" causes a .slideDown() animation on "data to reveal", with appropriate reverse logic attached for the data hiding as well.The page in question has 12 such sections, and writing the script long form (no loops) works fine. However, I would like to generalize this logic, but my first attempt at a loop to attach the DOM element callbacks does not work, and I suspect it's a scoping issue with java script:     for (var i = 1; i <= 12; i++) {          var eventElem = "#dataRevealLink" + i;          var actOnElem = "#dataToReveal" + i;         $(eventElem).click( function() {                               $(actOnElem).slideDown();                               return false;           // prevents the link from processing this click            });      }I suspect that in the above logic, the mouse-click callback is attaching to the dataRevealLink1-12 fine, however once inside the callback, "actOnElem" is not what I'm expecting - possibly due to the scope of actOnElem? I'm not entirely sure...I've added console.log() calls to the above logic, and everything is as I expect during the above looping, but I am never getting any of the callbacks to run, so I can never see any console.log() output from inside a mouse-click handler...Any advice anyone?-- View this message in context:http://www.nabble.com/JQuery-events-and-a-possible-scoping-error-on-m... Sent from the jQuery General Discussion mailing list archive at Nabble.com.

Re: JQuery events and a possible scoping error on my part?

by north-6 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


Hi Charlie,

one drawback of your function that I see is, that it only works if the
divs with the data to reveal have a simple ID count and appear in
sorted order in the code (i.e. dataToReveal1, dataToReveal2,
dataToReveal3 etc.). If you mix them up, or if you have more complex
IDs (for whatever reason - I admit this might be rather unlikely ;),
the function doesn't work properly anymore, since there is only a
loose connection between the link and the data div.

Just my five cents :)

On 4 Jul., 16:17, Charlie <charlie...@...> wrote:

> Cleaner if you can use a class on the links. Assume they now have class "dataReveal".
> i=1;
> $(".dataReveal").each(function () {
>         var actOnElem = "#dataToReveal" +i;
>            $(this).click( function() {         
>            $(actOnElem).slideDown();          
>             return false; 
>          });
>          i++;
>      });
> olsch01 wrote:OK, I guess this is one possible solution: $('a[id^=dataRevealLink]').each(function(){ var eventElemId = $(this).attr('id'); var eventElemIdNo = eventElemId.substring(14, eventElemId.length); var actOnElem = $('#dataToReveal' +eventElemIdNo); $(this).click(function() { actOnElem.slideDown(); return false; }) }); Cheers On 4 Jul., 12:59, olsch01<ollo...@...>wrote:Hi, I'm not a JS/jQuery expert, so as a quick test I added alert (actOnElem); inside your $(eventElem).click( function(), and the result always was #dataToReveal12. As mentioned, I am not an expert and still learning myself, but I think on dom ready the loop simply starts running until i equals 12. And it's not until then, that the click function comes into play. That's all I can say at the moment. If I have more time later, I will look into this again. Cheers On 4 Jul., 03:59, bsenftner<bsenft...@...>wrote:Just learning Java Script & JQuery, but an experienced developer, I've created a page with a series of elements that use the .slideDown() and .slideUp() functions to reveal and hide the different areas of content on the page.To facilitate this, the page's html uses links with ids similar to: { "dataRevealLink1", "dataToReveal1", "dataHideLink1" }. Clicking on a "data-reveal-link" causes a .slideDown() animation on "data to reveal", with appropriate reverse logic attached for the data hiding as well.The page in question has 12 such sections, and writing the script long form (no loops) works fine. However, I would like to generalize this logic, but my first attempt at a loop to attach the DOM element callbacks does not work, and I suspect it's a scoping issue with java script:     for (var i = 1; i <= 12; i++) {          var eventElem = "#dataRevealLink" + i;          var actOnElem = "#dataToReveal" + i;         $(eventElem).click( function() {                               $(actOnElem).slideDown();                               return false;           // prevents the link from processing this click            });      }I suspect that in the above logic, the mouse-click callback is attaching to the dataRevealLink1-12 fine, however once inside the callback, "actOnElem" is not what I'm expecting - possibly due to the scope of actOnElem? I'm not entirely sure...I've added console.log() calls to the above logic, and everything is as I expect during the above looping, but I am never getting any of the callbacks to run, so I can never see any console.log() output from inside a mouse-click handler...Any advice anyone?-- View this message in context:http://www.nabble.com/JQuery-events-and-a-possible-scoping-error-on-m... Sent from the jQuery General Discussion mailing list archive at Nabble.com.

Re: JQuery events and a possible scoping error on my part?

by Charlie Tomlinson :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

good point, if links are sortable would need to re think my method. Assumed they were in order in my example. If they are in order however there is less searching of the DOM required, especially if there are hundreds or thousands of <a> tags

olsch01 wrote:
Hi Charlie,

one drawback of your function that I see is, that it only works if the
divs with the data to reveal appear in sorted order in the code (i.e.
dataToReveal1, dataToReveal2, dataToReveal3 etc.). If you mix them up,
the function doesn't work properly anymore (at least not in my test),
since your just counting up i. So there is only a loose connection
between the link and the data div.

Doesn't necessarily have to been an issue though :)


On 4 Jul., 16:17, Charlie charlie...@... wrote:
  
Cleaner if you can use a class on the links. Assume they now have class "dataReveal".
i=1;
$(".dataReveal").each(function () {
        var actOnElem = "#dataToReveal" +i;
           $(this).click( function() {         
           $(actOnElem).slideDown();          
            return false; 
         });
         i++;
     });
olsch01 wrote:OK, I guess this is one possible solution: $('a[id^=dataRevealLink]').each(function(){ var eventElemId = $(this).attr('id'); var eventElemIdNo = eventElemId.substring(14, eventElemId.length); var actOnElem = $('#dataToReveal' +eventElemIdNo); $(this).click(function() { actOnElem.slideDown(); return false; }) }); Cheers On 4 Jul., 12:59, olsch01ollo...@...wrote:Hi, I'm not a JS/jQuery expert, so as a quick test I added alert (actOnElem); inside your $(eventElem).click( function(), and the result always was #dataToReveal12. As mentioned, I am not an expert and still learning myself, but I think on dom ready the loop simply starts running until i equals 12. And it's not until then, that the click function comes into play. That's all I can say at the moment. If I have more time later, I will look into this again. Cheers On 4 Jul., 03:59, bsenftner<bsenft...@...>wrote:Just learning Java Script & JQuery, but an experienced developer, I've created a page with a series of elements that use the .slideDown() and .slideUp() functions to reveal and hide the different areas of content on the page.To facilitate this, the page's html uses links with ids similar to: { "dataRevealLink1", "dataToReveal1", "dataHideLink1" }. Clicking on a "data-reveal-link" causes a .slideDown() animation on "data to reveal", with appropriate reverse logic attached for the data hiding as well.The page in question has 12 such sections, and writing the script long form (no loops) works fine. However, I would like to generalize this logic, but my first attempt at a loop to attach the DOM element callbacks does not work, and I suspect it's a scoping issue with java script:     for (var i = 1; i <= 12; i++) {          var eventElem = "#dataRevealLink" + i; &nbs
p;        var actOnElem = "#dataToReveal" + i;         $(eventElem).click( function() {          &nbsp&nbsp                   $(actOnElem).slideDown();          &nbsp&nbsp                   return false;           // prevents the link from processing this click          &nbsp&nbsp});      }I suspect that in the above logic, the mouse-click callback is attaching to the dataRevealLink1-12 fine, however once inside the callback, "actOnElem" is not what I'm expecting - possibly due to the scope of actOnElem? I'm not entirely sure...I've added console.log() calls to the above logic, and everything is as I expect during the above looping, but I am never getting any of the callbacks to run, so I can never see any 
console.log() output from inside a mouse-click handler...Any advice anyone?-- View this message in context:http://www.nabble.com/JQuery-events-and-a-possible-scoping-error-on-m... Sent from the jQuery General Discussion mailing list archive at Nabble.com.
    

  


Re: JQuery events and a possible scoping error on my part?

by north-6 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


Agreed :)

Re: JQuery events and a possible scoping error on my part?

by bsenftner :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


First off, I'd like to sincerely thank both olsch01 and charlie for  
their help, as well as the superb website of list member Karl  
Swedberg. Between their help and that web site, I have a completely  
generalized solution I am very happy with!

It was Karl's www.learningjquery.com site, and his article explaining  
"What is 'this'?" that gave me a complete grasp of what was going on.

So, now for any page that I want content to be available in sliding  
down and up sections, I do this:

1) any links for data to be revealed have the class "peekaboo"
2) each link for data to be revealed has an id of the form  
"reveal_someNumber", as in "reveal_1" and "reveal_3678"
3) each link for data to be hidden has an id of the form  
"hide_someNumber"
4) each block of content that gets revealed and hidden has an id of  
the form "peekaboo_someNumber"

And here's the jquery that makes the magic:

      // locate all page elements with the class "peekaboo":
      $(".peekaboo").each( function() {
                             // attach a click callback to our reveal-
link:
                             $(this).click( function() {
                                              var parts =  
this.id.split( "_" );
                                              $("#peekaboo_" + parts
[1]).slideDown();
                                              return false;
                                          });

                             // 'this' is an element of class  
'peekaboo',
                             // with an id holding key info:
                             var elems = this.id.split( "_" ); // id  
is of the form reveal_num

                             // attach a click callback to our hide-
link:
                             $("#hide_" + elems[1]).click( function() {
                                                                var  
parts = this.id.split( "_" );
                                                                $
("#peekaboo_" + parts[1]).slideUp();
                                                                 
return false;
                                                            });
                           } // close anonymous function each callback
                         );  // close 'each'


Sincerely,
-Blake
bsenftner@...


Re: JQuery events and a possible scoping error on my part?

by north-6 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


Glad you found your own solution so fast, Blake!

If you want to slide the info divs up and down using the same link,
you could also use the nice toogle function. Then you just have to do
something like this:

$(".peekaboo").each( function() {
        $(this).click( function() {
                var parts =  this.id.split( "_" );
  $("#peekaboo_" + parts[1]).toggle("slow");
                return false;
        })
});


On 4 Jul., 23:30, Blake Senftner <bsenft...@...> wrote:

> First off, I'd like to sincerely thank both olsch01 and charlie for  
> their help, as well as the superb website of list member Karl  
> Swedberg. Between their help and that web site, I have a completely  
> generalized solution I am very happy with!
>
> It was Karl'swww.learningjquery.comsite, and his article explaining  
> "What is 'this'?" that gave me a complete grasp of what was going on.
>
> So, now for any page that I want content to be available in sliding  
> down and up sections, I do this:
>
> 1) any links for data to be revealed have the class "peekaboo"
> 2) each link for data to be revealed has an id of the form  
> "reveal_someNumber", as in "reveal_1" and "reveal_3678"
> 3) each link for data to be hidden has an id of the form  
> "hide_someNumber"
> 4) each block of content that gets revealed and hidden has an id of  
> the form "peekaboo_someNumber"
>
> And here's the jquery that makes the magic:
>
>       // locate all page elements with the class "peekaboo":
>       $(".peekaboo").each( function() {
>                              // attach a click callback to our reveal-
> link:
>                              $(this).click( function() {
>                                               var parts =  
> this.id.split( "_" );
>                                               $("#peekaboo_" + parts
> [1]).slideDown();
>                                               return false;
>                                           });
>
>                              // 'this' is an element of class  
> 'peekaboo',
>                              // with an id holding key info:
>                              var elems = this.id.split( "_" ); // id  
> is of the form reveal_num
>
>                              // attach a click callback to our hide-
> link:
>                              $("#hide_" + elems[1]).click( function() {
>                                                                 var  
> parts = this.id.split( "_" );
>                                                                 $
> ("#peekaboo_" + parts[1]).slideUp();
>
> return false;
>                                                             });
>                            } // close anonymous function each callback
>                          );  // close 'each'
>
> Sincerely,
> -Blake
> bsenft...@...