Rectangle 27 4

In case your second page javascript is placed inside a HEAD content

If I understood you correctly, you are using ajax to load this page into the DOM? If this is true then I understand your problem. You see, when ajax is used for page loading only BODY content is loaded into the DOM.

You can fix your problem if you initialize your second html page javascript inside a first HTML file or move your SCRIPT block inside a second HTML BODY content.

Also, I have described this problem in my other ARTICLE with more details and few examples, or it can be found HERE.

This could also be a little different problem. You see, if you have 2 buttons with a same id, they are both inside a DOM structure. If you try to bind a click event on a second page button, that same event will be bound to the button on a first page. Because they have a same id jQuery will bound an event to the first button (with that id) found in the DOM.

To fix this problem you need to use a jQM constructor called active page. One more warning, next code example will work only in a page events initialized after a pageinit event, for example pagebeforeshow or pageshow events:

$(document).on('pagebeforeshow', '#yourPageID', function(){     
    // Registering button click  
    $(document).on('click', $.mobile.activePage.find('#myButtonID'), function(){
        // Do something
    });
});

This line of code:

$.mobile.activePage.find('#myButtonID')

Will only get button '#myButtonID' found in a current active page, no matter how many other buttons with a same id exist inside the DOM.

About your last questions. It doesn't matter which template structure you use (1 HTML with multiple pages or multiple HTML's), you just need to worry about things I mentioned before.

Phonegap - jquery Mobile : button click event not able catch in androi...

android jquery jquery-mobile cordova
Rectangle 27 1

The content loaded (supposedly through Ajax) is rendered as a text string. It's up to you to load it into the DOM using .innerHTML and such. In jQuery you can use .html() to load the content inside the DOM and then you're going to be able to access it through standard jQuery DOM selectors.

it is walkaround, but point is in using dynamical loading. file is big, should be loaded only when neded

jQuery should interpret the loaded content as HTML, there shouldn't be a need for doing anything else manually. api.jquery.com/load

javascript - jQuery make loaded file part of DOM - Stack Overflow

javascript jquery
Rectangle 27 34

A Windows load event fires when all the content on your page is fully loaded including the DOM (document object model) content and asynchronous JavaScript, frames and images. You can also use body onload=. Both are the same; window.onload = function(){} and <body onload="func();"> are different ways of using the same event.

jQuery $document.ready function event executes a bit earlier than window.onload and is called once the DOM(Document object model) is loaded on your page. It will not wait for the images, frames to get fully load.

$document.ready()
window.onload()

javascript - window.onload vs $(document).ready() - Stack Overflow

javascript jquery javascript-events unobtrusive-javascript
Rectangle 27 34

A Windows load event fires when all the content on your page is fully loaded including the DOM (document object model) content and asynchronous JavaScript, frames and images. You can also use body onload=. Both are the same; window.onload = function(){} and <body onload="func();"> are different ways of using the same event.

jQuery $document.ready function event executes a bit earlier than window.onload and is called once the DOM(Document object model) is loaded on your page. It will not wait for the images, frames to get fully load.

$document.ready()
window.onload()

javascript - window.onload vs $(document).ready() - Stack Overflow

javascript jquery javascript-events unobtrusive-javascript
Rectangle 27 2

As I understand it, you are looking to use jQuery load() or an equivalent AND have the browser history (address bar) update to reflect the url of the just loaded content.

Since you suggest that you have load() working, then what you are after is the browser History_API, specifically pushState().

You can read more about the : History_API

You can also read about the : pushState() method

Based on your load() example, I think you can extend it with the following to get what you are after:

$('#content').load('link1.html');
$('a').click(function(e){
  var page = $(this).attr('href');
  $('#content').load(page + '.html');

  var stateObj = {loaded : page};
  history.pushState(stateObj, "page title", page + '.html');

  return false; // don't follow the link
});

You can also see Mozilla's AJAX based navigation example that does what I think you are looking to do via AJAX rather than jQuery and uses pushstate.

javascript - jQuery/Ajax Load external page into content div - Stack O...

javascript jquery ajax load
Rectangle 27 37

You are correct in your understanding of the DOM based model. The XML file will be loaded as a whole and all it's contents will be built as an in-memory representation of the tree the document represents. This can be time- and memory-consuming, depending on how large the input file is. The benefit of this approach is that you can easily query any part of the document, and freely manipulate all the nodes in the tree.

The DOM approach is typically used for small XML structures (where small depends on how much horsepower and memory your platform has) that may need to be modified and queried in different ways once they have been loaded.

SAX on the other hand is designed to handle XML input of virtually any size. Instead of the XML framework doing the hard work for you in figuring out the structure of the document and preparing potentially lots of objects for all the nodes, attributes etc., SAX completely leaves that to you.

What it basically does is read the input from the top and invoke callback methods you provide when certain "events" occur. An event might be hitting an opening tag, an attribute in the tag, finding text inside an element or coming across an end-tag.

SAX stubbornly reads the input and tells you what it sees in this fashion. It is up to you to maintain all state-information you require. Usually this means you will build up some sort of state-machine.

While this approach to XML processing is a lot more tedious, it can be very powerful, too. Imagine you want to just extract the titles of news articles from a blog feed. If you read this XML using DOM it would load all the article contents, all the images etc. that are contained in the XML into memory, even though you are not even interested in it.

With SAX you can just check if the element name is (e. g.) "title" whenever your "startTag" event method is called. If so, you know that you needs to add whatever the next "elementText" event offers you. When you receive the "endTag" event call, you check again if this is the closing element of the "title". After that, you just ignore all further elements, until either the input ends, or another "startTag" with a name of "title" comes along. And so on...

You could read through megabytes and megabytes of XML this way, just extracting the tiny amount of data you need.

The negative side of this approach is of course, that you need to do a lot more book-keeping yourself, depending on what data you need to extract and how complicated the XML structure is. Furthermore, you naturally cannot modify the structure of the XML tree, because you never have it in hand as a whole.

So in general, SAX is suitable for combing through potentially large amounts of data you receive with a specific "query" in mind, but need not modify, while DOM is more aimed at giving you full flexibility in changing structure and contents, at the expense of higher resource demand.

xml parsing - What is the difference between SAX and DOM? - Stack Over...

xml-parsing saxparser domparser
Rectangle 27 36

You are correct in your understanding of the DOM based model. The XML file will be loaded as a whole and all it's contents will be built as an in-memory representation of the tree the document represents. This can be time- and memory-consuming, depending on how large the input file is. The benefit of this approach is that you can easily query any part of the document, and freely manipulate all the nodes in the tree.

The DOM approach is typically used for small XML structures (where small depends on how much horsepower and memory your platform has) that may need to be modified and queried in different ways once they have been loaded.

SAX on the other hand is designed to handle XML input of virtually any size. Instead of the XML framework doing the hard work for you in figuring out the structure of the document and preparing potentially lots of objects for all the nodes, attributes etc., SAX completely leaves that to you.

What it basically does is read the input from the top and invoke callback methods you provide when certain "events" occur. An event might be hitting an opening tag, an attribute in the tag, finding text inside an element or coming across an end-tag.

SAX stubbornly reads the input and tells you what it sees in this fashion. It is up to you to maintain all state-information you require. Usually this means you will build up some sort of state-machine.

While this approach to XML processing is a lot more tedious, it can be very powerful, too. Imagine you want to just extract the titles of news articles from a blog feed. If you read this XML using DOM it would load all the article contents, all the images etc. that are contained in the XML into memory, even though you are not even interested in it.

With SAX you can just check if the element name is (e. g.) "title" whenever your "startTag" event method is called. If so, you know that you needs to add whatever the next "elementText" event offers you. When you receive the "endTag" event call, you check again if this is the closing element of the "title". After that, you just ignore all further elements, until either the input ends, or another "startTag" with a name of "title" comes along. And so on...

You could read through megabytes and megabytes of XML this way, just extracting the tiny amount of data you need.

The negative side of this approach is of course, that you need to do a lot more book-keeping yourself, depending on what data you need to extract and how complicated the XML structure is. Furthermore, you naturally cannot modify the structure of the XML tree, because you never have it in hand as a whole.

So in general, SAX is suitable for combing through potentially large amounts of data you receive with a specific "query" in mind, but need not modify, while DOM is more aimed at giving you full flexibility in changing structure and contents, at the expense of higher resource demand.

xml parsing - What is the difference between SAX and DOM? - Stack Over...

xml-parsing saxparser domparser
Rectangle 27 10

Your first problem is point where you are trying to initialize JavaScript. From your previous answers I can see you are using several HTML/ASP pages and all of your javascript is initialized form the page <head>. This is the main problem. Only the first HTML file should have JavaScript placed into the <head> content. When jQuery Mobile loads other pages into the DOM it loads only the <div> with a data-role="page" attribute. Everything else, including <head>, will be discarded.

This is because currently loaded page has a <head> already. No point in loading another pages <head> content. This goes even further. If you have several pages in a second HTML file, only the first one is going to be loaded.

I will not try to invent warm water here so here are links to my other 2 answers discussing this problem. Several solutions can be found there:

  • Put all of your JavaScript into a first HTML/ASP file
  • Move your JavaScript into <body>; to be more precise, move it into a <div> with data-role="page". As I already pointed out, this is the only part of a page that is going to be loaded.
  • Use rel="external" when switching between pages because it will trigger a full page refresh. Basically, you jQuery mobile that the page will act as a normal web application.

As Archer pointed out, you should use page events to initialize your code. But let me tell you more about this problem. Unlike classic normal web pages, when working with jQuery Mobile, document ready will usually trigger before page is fully loaded/enhanced inside the DOM.

That is why page events were created. There are several of them, but if you want your code to execute only once (like in case of document ready) you should use the pageinit event. In any other case use pagebeforeshow or pageshow.

If you want to find out more about page events and why they should be used instead of document ready take a look at this article on my personal blog. Or find it here.

JavaScript in jQuery mobile not working unless I refresh - Stack Overf...

javascript jquery ajax jquery-mobile
Rectangle 27 4

Since your script uses jQuery, you can simply use the $(document).ready() and $(window).load() functions of jQuery to bind a function on the event that DOM is ready and all window contents have been loaded, respectively.

If you do not use jQuery, take a look at these relative questions to understand how to imitate the above behaviour with pure JS:

EDIT 1: The inclusion order matters. You have to include the jQuery scripts before any scripts that require jQuery are executed.

EDIT 2: You can organize your templates better by keeping the scripts separately from the main content, either with a second template:

<script src="jquery.js"></script>
<script src="awesome-script.js"></script>
<script>
    $(document).ready(function(){
        ...
    });
</script>
base.html

Or with blocks (recommended):

<!DOCTYPE html>
<html>

<head>...</head>
<body>
    {% block content %}{% endblock %}
    {% block scripts %}{% endblock %}
</body>
</html>
{% extends 'base.html' %}
{% block content %}
    ...
{% endblock %}
{% block scripts %}
    <script src="jquery.js"></script>
    <script src="awesome-script.js"></script>
    <script>
        $(document).ready(function(){
            ...
        });
    </script>
{% endblock %}
content.html

Thanks. I do use jQuery but it's not loaded yet so '$' is not defined when calling $(document)

Welcome, you simply have to include the jquery script before your script.

It's already the case. In base.html, Jquery is loaded, then my script is loaded. But when entering into my main content, no JS is loaded at all (which is normal)

What do you mean "entering main content"? Post the lines where you include jquery please.

javascript - Django/jQuery: handling template inheritence and JS files...

javascript jquery python django django-templates
Rectangle 27 7

This is the expected behavior of the load method, it'll always download the entire content. You can specify that a certain part of the loaded page be parsed and placed into the calling container.

jQuery('#tips').load('url #tip1');

thanks Jay. also is there a way to stop IE caching of ajax request sent using .load. I can see ajaxsetup to stop caching but is it possible for single ajax query only.

jQuery("#tips").load("/tips/?cachebuster=" + Math.floor(Math.random()*10001) +" #randomtips");

@Jay Blanchard Hey, that's awesome, I'm very new to AJAX and I always used the AJAX call to go to a separate server-side page with no content, save that which I would dynamically plot and subsequently want returned. I didn't know you could parse by the id of the element like that. Thanks for teaching me something!

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - Ajax call returning whole page - Stack Overflow

javascript jquery ajax wordpress
Rectangle 27 7

This is the expected behavior of the load method, it'll always download the entire content. You can specify that a certain part of the loaded page be parsed and placed into the calling container.

jQuery('#tips').load('url #tip1');

thanks Jay. also is there a way to stop IE caching of ajax request sent using .load. I can see ajaxsetup to stop caching but is it possible for single ajax query only.

jQuery("#tips").load("/tips/?cachebuster=" + Math.floor(Math.random()*10001) +" #randomtips");

@Jay Blanchard Hey, that's awesome, I'm very new to AJAX and I always used the AJAX call to go to a separate server-side page with no content, save that which I would dynamically plot and subsequently want returned. I didn't know you could parse by the id of the element like that. Thanks for teaching me something!

javascript - Ajax call returning whole page - Stack Overflow

javascript jquery ajax wordpress
Rectangle 27 3

Yes, jQuery Mobile does "mess with the DOM" when it's loaded. For example, jQuery Mobile will wrap your content in a "page" div:

Behind the scenes, the framework will inject the page wrapper if it's not included in the markup because it's needed for managing pages (Pages - jQuery Mobile Docs)

But you could see if it's the CSS or the Javascript that's breaking your site by including only one of the jQuery Mobile bits at a time.

I too am getting the same warning regarding the call to getElementById(), and I can confirm that it is just a warning and does not impact layout. I have asked specifically about getting rid this warning, but to no avail.

Finally, have you tried using jQuery Mobile's custom builder to get just the parts you are interested in (i.e. the touch features)?

Yup. jQuery Mobile had hijacked my DOM with a load of classes and some divs. Firefox is a lot more affected by wrapping elements than Chrome seems to be. They seem to interpret the box model differently, especially in regards to height.

javascript - JQuery Mobile and Firefox don't play well together? - Sta...

javascript jquery html jquery-mobile
Rectangle 27 3

The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate, and the DOM ready handler only executes for the first page. To execute code whenever a new page is loaded and created, you can bind to the pageinit event. This event is explained in detail at the bottom of this page.

Only for me, "pageinit" wasn't working, but "pagechange" did the trick.

So what I wound up doing was the following: extracting my original code from $(document).ready() and inserting it into a separate function. It now looks like this:

$(document).ready(DocumentReady);

$(document).bind("pagechange", function () {
    // check if we just logged out to ensure we don't call DocumentReady() 
    // twice in succession
    if (window.location.href.indexOf("LogOff") > -1) {
        DocumentReady();
    }
});

function DocumentReady() {
    // some initialization code
});

This solved the first problem of my javscript not executing, but my UI was not showing the changes made by the javascript.

As the JQM docs state, the whole app is working in a single document. So my LogOff controller method (which redirected to LogOn) was causing a new login page to be injected (or appended) into the existing page. Then when my javascript code would, say, access a text input field with $("#userField"), it was accessing the field from the page which loaded at the very beginning of the application, not the one being displayed after logging out!

What I figured out later is that changing the page location by assigning a value to window.location causes a full refresh. So when logging out, rather than call a controller method, I can just do this:

$("#logoutBtn").click(function () {
    window.location = $.mobile.path.parseUrl(window.location.href).domain + "/Account/LogOn";
});

Since this causes the page to refresh completely, the $(document).ready() event is fired, meaning that what I said previously about binding to "pagechange" or "pageinit" is no longer necessary, though still very good to know about when working with jQuery mobile. The refresh also loads up a brand new DOM, so I can be certain that my javascript will affect the elements displayed on the page.

asp.net mvc 3 - Javascript doesn't execute in view after a controller ...

javascript asp.net-mvc-3 jquery-mobile
Rectangle 27 2

When content of the modal is dynamic, Select2 assets will not be loaded because initially there is no Select2 related code in DOM.

1) You can register Select2 assets in advance by calling:

\kartik\select2\Select2Asset:register($this);

And then you need to initialize Select2 on every modal content change by calling something like:

$('#field-id').select2();

2) Instead of replacing all HTML inside modal, just render it in advance including empty select (or with some initial data) and only change data inside of it after clicking on different modal triggers.

$dependentDropdown.find('option:not([value=""])').remove();
$dependentDropdown.select2('val', '');
// This can come from AJAX request
var data = [
    {'id': 1, 'text': 'Some text 1'},
    {'id': 2, 'text': 'Some text 2'}
],
var html = '';
$.each(data, function(key, value) {
    html += '<option value="' + value.id + '">' + value.text + '</option>';
});
$dependentDropdown.append(html);

jquery - yii2 kartik select2 plugin doesnt work in modal - Stack Overf...

jquery yii2 bootstrap-modal jquery-select2
Rectangle 27 2

When content of the modal is dynamic, Select2 assets will not be loaded because initially there is no Select2 related code in DOM.

1) You can register Select2 assets in advance by calling:

\kartik\select2\Select2Asset:register($this);

And then you need to initialize Select2 on every modal content change by calling something like:

$('#field-id').select2();

2) Instead of replacing all HTML inside modal, just render it in advance including empty select (or with some initial data) and only change data inside of it after clicking on different modal triggers.

$dependentDropdown.find('option:not([value=""])').remove();
$dependentDropdown.select2('val', '');
// This can come from AJAX request
var data = [
    {'id': 1, 'text': 'Some text 1'},
    {'id': 2, 'text': 'Some text 2'}
],
var html = '';
$.each(data, function(key, value) {
    html += '<option value="' + value.id + '">' + value.text + '</option>';
});
$dependentDropdown.append(html);

jquery - yii2 kartik select2 plugin doesnt work in modal - Stack Overf...

jquery yii2 bootstrap-modal jquery-select2
Rectangle 27 3

Yes, I think that the DOM and content scripts are reloaded every time the panel is shown (you can easily test whether that's correct, just put a console.log("loaded") call into your content script). So you should simply send your message when the panel is shown:

var prefPanel = panel.Panel({
    contentURL: self.data.url('prefPanel.html'),
    contentScriptFile: self.data.url('prefPanel.js'),
    contentScriptWhen: 'ready',
    onMessage: function(message) {
        switch(message.method) {
            case 'setValue':
                ss.storage[message.key] = message.value;
        }
    },
    onShow: function() {
        prefPanel.sendMessage(ss.storage);
    }
});

javascript - Firefox Addons SDK - How to access simple storage from co...

javascript firefox firefox-addon firefox-addon-sdk
Rectangle 27 1

You need to wire up the click events to the href's when the new dynamic content has been loaded into the DOM.

When the page loads, JQuery will look through the DOM for your $("#TestButton") and find nothing as at the time when this happens the dynamic content has yet to be injected.

There are a couple of ways of handling this... firstly you can delay the wire up of the click events with JQuery until the new content has been injected, or you can use the .live function of JQuery.

$("#TestButton").live('click', function (ev) {
        ev.preventDefault()

        alert('Test Button Clicked'); 
    });

Actually... it seems Live has been depreciated as of JQuery 1.7

$("#TestButton").on('click', function (ev) {
            ev.preventDefault()

            alert('Test Button Clicked'); 
        });

asp.net mvc - Accessing twitter bootstrap modal-body content with jque...

jquery asp.net-mvc twitter-bootstrap modal-dialog
Rectangle 27 1

You need to wire up the click events to the href's when the new dynamic content has been loaded into the DOM.

When the page loads, JQuery will look through the DOM for your $("#TestButton") and find nothing as at the time when this happens the dynamic content has yet to be injected.

There are a couple of ways of handling this... firstly you can delay the wire up of the click events with JQuery until the new content has been injected, or you can use the .live function of JQuery.

$("#TestButton").live('click', function (ev) {
        ev.preventDefault()

        alert('Test Button Clicked'); 
    });

Actually... it seems Live has been depreciated as of JQuery 1.7

$("#TestButton").on('click', function (ev) {
            ev.preventDefault()

            alert('Test Button Clicked'); 
        });

asp.net mvc - Accessing twitter bootstrap modal-body content with jque...

jquery asp.net-mvc twitter-bootstrap modal-dialog
Rectangle 27 1

Since You're inserting into the DOM, all JS loaded via XHR is in the window scope automatically and afaik, there's no proper way around that. All the context option of $.ajax() does, is setting the value of this in the callback function.

One possible, although very very quirky way around the problem would be to set a global variable that you can call later (something along these lines):

var context;

$(function(){
   context = $('whatever');
   $.ajax({
      url: '/myAjaxResponse.html',
      success: function(resp) { $("#mydiv").html(resp); }
   });
});
<script type="text/javascript">
    $this = context;
    console.log($this);   // $this points to whatever you set context to before XHR
</script>

To make a long story short: $(this), in the context of your $.ajax() call, does indeed point to window.

You could/should either go with

$(function(){
   $.ajax({
      url: '/myAjaxResponse.html',
      context: $('#mydiv'),
      success: function(resp) { $("#mydiv").html(resp); }
   });
});

or (somewhat quirkily) with

$(function(){
   $('#mydiv').each(function(){
       $.ajax({
          url: '/myAjaxResponse.html',
          context: $(this),
          success: function(resp) { $("#mydiv").html(resp); }
       });
   })
});

where this points to the element being iterated over by $.each().

"all JS loaded via XHR is in the window scope automatically" Precisely.

ah, my bad (typo), yes, in the $.ajax({context: $("#mydiv)... }) is what I meant :) So, the only way is by global vars right? :( So, if build some uid, attach it to the #mydiv data and "select" based on that uid it should work right? (Will also read the provided link - thanks :)

javascript - jQuery ajax mixed html/js