Search code examples
jquery-mobile

Jquery Mobile Javascript not working on ajax load


Have the following markup in my html page to toggle a search bar based on if a search icon is clicked:

<a id="searchIcon" href="/"></a> 

<div id="searchWrapOuter" style="display:none;">
    <div id="searchWrapInner">
        <div id="formContainer">
            <form id="searchForm" action="#">
                <div>
                    <input type="search" name="search-mini" id="search-mini" value="" data-mini="true" />
                </div>
            </form>
        </div>
    </div>
</div>

Width the following javascipt/jquery:

 $(function() {
        $(document).on("click", "#searchIcon", function () {
            var searchWrapper = $("#searchWrapOuter");
            $(searchWrapper).slideToggle();
            return false;
        });
});

This code works as expected on a page load direct off a Url. When coming into the page off a link which is Ajax loaded, loads the contents of the page into the DOM, and the DOM ready handler only executes for the first page.

I have read about using the

$(document).on('pageinit'), not $(document).ready()/$(function()

I still haven't been able to get this to work when coming in off an ajax link however. What would be the correct way to implement these events to get the code to work coming in from an Ajax link?

Thanks,


Solution

  • Most likely it is because you are using IDs instead of classes. jQuery Mobile doesn't work well with IDs because it caches pages into the DOM so if you open a page, close it, then go back to the page, you might have your page twice inside the DOM (one visible, one hidden/cached). So when you do $("#searchWrapOuter") you don't know which element you are actually dealing with (in your case, probably the hidden one).

    The solution is to change your IDs to classes. This is not very intuitive but I found that is the best way to work with jQuery Mobile.

    Also note this comment in the doc which might also be relevant to you:

    The id attribute of all your elements must be not only unique on a given page, but also unique across the pages in a site. This is because jQuery Mobile's single-page navigation model allows many different "pages" to be present in the DOM at the same time. This also applies when using a multi-page template, since all "pages" on the template are loaded at once.

    http://jquerymobile.com/demos/1.2.0/docs/pages/page-anatomy.html