0

I have combined a search function with a jQueryUI accordion.
The search function highlights the title of every section that the inputted search term is found. I am trying to figure out a way to have the viewport scroll to the first occurrence of a found term when a section is opened, saving the user having to scroll through potentially very long content.
Each highlighted term is wrapped in <span class="highlight"&gt;term&lt;/span>. I have got to the point where I've added an onclick="jumpTo(chapter_number)" handler to each section header when a term is found within it. I just need help with the jumpTo function. Thank you!

Here's my fiddle: http://jsfiddle.net/jameshuckabonetech/YsdDn/

P.S. Fiddle is great! First one ...

UPDATE Finished working code ...

$( "#accordion" ).accordion(
{
    autoHeight: false, collapsible: true, active: false,
    activate:function(event, ui )
    {
        if ($(ui.newPanel).find('.highlight').length>0 && $("#jump-box").prop('checked') == true)
            $('html, body').animate(
            {
                scrollTop: $(ui.newPanel).find('.highlight').offset().top
            }
            , 2000);
    }
});
James Huckabone
  • 553
  • 1
  • 10
  • 32
  • 1
    You're going to need to add a bit more code for us to work with. A jsfiddle.net example of where you are right now is very useful. – idrumgood May 02 '13 at 18:59

1 Answers1

2

Don't use onclick use the accordion's activate event.

$( "#accordion" ).accordion({
    autoHeight: false, collapsible: true, active: false,
    activate:function(event, ui ){
       if ($(ui.newPanel).find('.highlight').length>0)
          $('html, body').animate({
              scrollTop: $(ui.newPanel).find('.highlight').offset().top
              }, 2000);
    },
    beforeActivate:function(e,ui)
    {
        //if statement to check if you want to stop the accordion from opening
        e.preventDefault();
    }
});

Used the scrolling code from jQuery scroll to element

Community
  • 1
  • 1
user694844
  • 1,168
  • 12
  • 16
  • thank you, that worked (when I update jqueryui to 1.9.2 [had 1.8.2]). However, how do I cancel the function onclick of something? – James Huckabone May 03 '13 at 21:24
  • i get an error $(...).find(...).offset(...) is undefined --- any ideas? – James Huckabone May 03 '13 at 22:25
  • It works on the fiddle you provided. Something isn't named the same. Most likely the `highlight` class. Or the panel doesn't have any highlighted items. Step through part of the statement using a javascript debugger to find the missing part. Edited to fix errors when there is no highlighted items. – user694844 May 06 '13 at 16:13
  • Just wanted to say thank you again. I was using a messy pile of if statements that this totally alleviates. I just want to clarify one thing: by "cancel the function" I meant "turn off the scrolling if a radio box gets unchecked". Edited question to include working example above ... – James Huckabone May 07 '13 at 07:04