I am looking to find a way to have jQuery Mobile render data being loaded onto the page. I know that very similar topics has been discussed mn the past, but nothing seems to be a perfect match (or close enough to result in me finding an answer).
The issue is that jQuery mobile will dynamically apply classes to HTML elements when a page is loaded. Content being pulled in through JavaScript does not get transformed because the process is run before the JavaScript content is placed onto the page. The fix for this supposedly is to use the .trigger('create') function. It seems though that this doesn't work when you use the load() function to pull content from external pages.
I am able to get the data from the twitter.html file (example below) just fine, it just isn't being formatted via jQuery Mobile
To help demonstrate my point, I've tried to put together some starter examples of the script. Unfortunately because I am loading an external file there is no easy way to represent this issue without saving the files to your computer to test them out.
Main file (index.html)
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="http://jquerymobile.com/demos/1.1.1/js/jquery.mobile-1.1.1.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="http://jquerymobile.com/demos/1.1.1/css/themes/default/jquery.mobile-1.1.1.css" />
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function(){
$('#container').load('twitter.html');
$('#container').trigger('create');
});
});//]]>
</script>
</head>
<body>
<div data-role="page" class="type-home">
<div data-role="content">
<!-- Load the Twitter Data -->
<div id="container"></div>
<ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="f">
<li data-role="list-divider">Sample</li>
<li>Ignore this</li>
<li>And look for Twitter data above</li>
</ul>
</div><!--/content-->
</div>
</body>
</html>
File being called (twitter.html)
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function($) {
var url = "http://search.twitter.com/search.json?callback=?&rpp=10&q='jquery'";
$.getJSON( url, function( data ) {
var twitterList = $( "<ul data-role='listview' data-inset='true' data-theme='c' data-dividertheme='b' />" );
$.each( data.results, function( index, item ) {
$( "<li />", { "text" : item.text } )
.appendTo( twitterList );
});
$( "#tweets" ).fadeOut( "fast", function(){
$( this ).empty()
.append( twitterList )
.fadeIn( "slow" );
});
});
});
</script>
<div id="tweets">Loading Tweets...</div>
Can anyone provide an example of a working method to call a file in this way?
Pages that I've looked into related to this:
I have like 10 pages to reference, but I'm a noob on this site so I am limited to just 2.
http://blog.stikki.me/2011/08/18/loading-dynamic-content-in-jquery-mobile-with-jquerys-load-function/
http://blog.dkferguson.com/index.cfm/2011/3/15/jQuery-Mobile-styling-loaded-content
I've literally spent the past 7 hours trying to work this out, so any help would be greatly appreciated. I am brand new to the world of JavaScript, so please take it easy on me.
As you know, In JQM, the loaded pages are not suppose to use $(document).ready. If you are in control of the page that is coming from the external source, than please modify the function to pageInit, otherwise, you will need a way to hook into the function call that external page is making.
Try extending the functions that downloaded page is calling. In this example: $.getJSON. In the extended function, wrap success function with your function that does pageCreate after executing the success function.
JQM Reference:
You have to either trigger "refresh" event on updated elements, or "create" on parent element of newly added added elements after you've changed the HTML. E.g. $('ul').listview('refresh').
Related
I'm new to JavaScript and I'm sure that this is a very trivial fix.
I'm dynamically changing a div content based on which button is clicked. This example works in JSFiddle but however when I put it on my PC it simply loads the entire webpage even when I wrap the JS with $(window).load(function(){ ... })
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src= "http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<ul class="menu">
<li>About</li>
<li>Contact</li>
<li>Misc</li>
</ul>
<div id="about" class="menu-content">About</div>
<div id="contact" class="menu-content">Contact</div>
<div id="misc" class="menu-content">Misc</div>
</body>
</html>
My JS (script.js):
$(window).load(function(){
var $content = $('.menu-content');
function showContent(type) {
$('div', $content).hide();
$('div[data-menu-content='+type+']').show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
});
$(window).load(function(){ ... })
replace by :
$(document).ready(function(){ ... })
Replace your (window).load to (document).ready
load is called when all assets are done loading, including images. ready is fired when the DOM is ready for interaction.
load()
The load event fires at the end of the
document loading process. At this
point, all of the objects in the
document are in the DOM, and all the
images and sub-frames have finished
loading.
ready()
While JavaScript provides the load
event for executing code when a page
is rendered, this event does not get
triggered until all assets such as
images have been completely received.
In most cases, the script can be run
as soon as the DOM hierarchy has been
fully constructed. The handler passed
to .ready() is guaranteed to be
executed after the DOM is ready, so
this is usually the best place to
attach all other event handlers and
run other jQuery code. When using
scripts that rely on the value of CSS
style properties, it's important to
reference external stylesheets or
embed style elements before
referencing the scripts.
try this
$(document).ready(function(){
var $content = $('.menu-content');
function showContent(type) {
$('div', $content).hide();
$('div[data-menu-content='+type+']').show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
});
You can try below solution :
function showContent(type) {
$($content).hide();
$('#'+type).show();
}
When i ran your snippet in my PC, I found out that Jquery was not able to find div, based on the selectors you have specified at the time of loading.
I wrote a small page with jQuery and an external .js file. But it won't load the jQuery part. Here my Code:
<!DOCTYPE html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/testScript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<button id="testBtn">Oh my Goood...</button>
<div id="testDiv">testText</div>
</body>
</html>
And here is my external Script:
alert("no jQuery");
$("button#testBtn").click(function(){
alert("Works!");
});
As you can see, jQuery will load before all other scripts. The alert pops up fine. But if I click the button, nothing happens. If I put the script inside the html document directly, the button event works as expected.
I reviewed these questions: Link and Link. But still not working as expected.
Instead of using the $(document).ready() method, you could also just move your javascript references to the bottom of the page, right above the </body> tag. This is the recommended way to include javascript in webpages because loading javascript blocks the page rendering. In this case it also makes sure the elements are already rendered when the javascript is executed.
You'll need to add the click function inside document ready.
$(document).ready(function(){
$("button#testBtn").click(function(){
alert("Works!");
});
});
Your method fails because the code is being executed as the page is being loaded and the elements it refers to haven't been loaded yet. Using $(document).ready holds the function execution till the DOM elements are ready.
Let me start off by saying my bootstrap modal load remote works fine. My particular problem is that it loads the whole remote URL as the HTML result, and I just need some specific sections from that HTML. For instance, lets say my remote URL is like this:
<html lang="en">
<head>
{head content goes here}
</head>
<body>
{some content here}
<div id="myContent1">{more content here}</div>
...
<div id="myContent2">{even more content here}</div>
</body>
</html>
So, instead of loading all above html code inside my modal, I just want to display divs #myContent1 and #myContent2.
Use Jquery ajax functions:
$( "#myContent1" ).load( "ajax/test1.html" );
$( "#myContent2" ).load( "ajax/test2.html" );
Using page fragments you can load specific divs to specific divs.
For example
$('#mainContainer').load('loadpage.html #nav1div');
Will load stuff inside your mainContainer that appear inside the div nav1div from the loaded page ('loadpage.html'), for more info check out http://api.jquery.com/load/
I am currently embedding a third-party javascript file directly on my page.
However, the website I'm embedding it from takes a while to respond so it stops the rendering of my site for several seconds.
I'm currently embedding it on my page on the spot where it will write some values:
<script language="javascript" type="text/javascript" src="[third-party site/file.js]"></script>
The response from the embedded script is just some JavaScript:
document.write('<div class="value">Value 1</div><div class="value">Value 2</div>');
I was thinking that after the page loads use jQuery to make an AJAX request and somehow parsing the response so I can get the values I need.
Is there be a better approach?
You can place this script inside a hidden element on the end of the body (just before </body>) and, after the page has loaded, move it to the desired location with jQuery.
<div id="hiddenElement">
<script type="text/javascript" src="[third-party site/file.js]"></script>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#hiddenElement").appendTo("#someOtherElement");
});
</script>
</body>
Another solution would be to use jQuery .getScript() to load the script in the desired location as you said and #James McDonnell said.
$(document).read(function()
{
$.getScript(/* src */)
});
This will run after the page has loaded.
$.getScript()
Perhaps this could be part of your solution. Here is a stand-alone jQuery example where a button is used to trigger a change event on a DIV. This example just shows you how to access the html content of the div and to see how to manipulate/change it. This is not a solution for you but parts of it might be useful when combined with rcdmk's and James' ideas.
<html>
<head>
<!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>-->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#button_test').click(function() {
$('.value').html('New stuff').change();
});
$('.value').change(function(){
$('div').each(function() {
alert($(this).html());
});
});
});
</script>
</head>
<body>
<div class="value">Value 1</div>
<div class="value">Value 2</div>
<button id="button_test">Click me</button>
This is an error in Firebug I keep seeing.
TypeError: $("#gallery-nav-button") is null
[Break On This Error]
$('#gallery-nav-button').addClass('animated fadeOutRightBig');
Here is my code:
JS
$(function() {
$("#close-gallery-nav-button").click(function() {
$('#gallery-nav-button').addClass('animated fadeOutRightBig');
});
});
HTML
<div id="gallery-nav-button">
<h4 id="close-gallery-nav-button">X</h4>
<h3 class="text-center small-text"><a class="inline text-center small-text" href="#gallery-nav-instruct">Click Here for Gallery <br /> Navigation Instructions.</a></h3>
</div>
CSS
#close-gallery-nav-button{
text-indent:-9999px;
width:20px;
height:20px;
position:absolute;
top:-20px;
background:url(/images/controls.png) no-repeat 0 0;
}
#close-gallery-nav-button{background-position:-50px 0px; right:0;}
#close-gallery-nav-button:hover{background-position:-50px -25px;}
I also want to add - because this is the #1 Google search result for the important error message "TypeError: [x] is null" - that the most common reason a JavaScript developer will get this is that they are trying to assign an event handler to a DOM element, but the DOM element hasn't been created yet.
Code is basically run from top to bottom. Most devs put their JavaScript in the head of their HTML file. The browser has received the HTML, CSS and JavaScript from the server; is "executing"/rendering the Web page; and is executing the JavaScript, but it hasn't gotten further down the HTML file to "execute"/render the HTML.
To handle this, you need to introduce a delay before your JavaScript is executed, like putting it inside a function that isn't called until the browser has "executed" all of the HTML and fires the event "DOM ready."
With raw JavaScript, use window.onload:
window.onload=function() {
/*your code here*
/*var date = document.getElementById("date");
/*alert(date);
}
With jQuery, use document ready:
$(document).ready(function() {
/*your code here*
/*var date = document.getElementById("date");
/*alert(date);
});
This way, your JavaScript won't run until the browser has built the DOM, the HTML element exists (not null :-) ) and your JavaScript can find it and attach an event handler to it.
I have several scripts running on this page and evidently one script was conflicting with another. To solve my issue I added jQuery.noConflict();
var $j = jQuery.noConflict();
$j(function() {
$j("#close-gallery-nav-button").click(function() {
$j('#gallery-nav-button').addClass('animated fadeOutRightBig');
});
});
As additional comment on #1 solution:
Another possibility for loading the script after finishing/building the HTML should be placing a defer parameter inside the script tag:
<script defer type="text/javascript" src="x.js"></script>
I agree with the advice given above, relating to the onload event. https://stackoverflow.com/a/18470043/2115934
A more simple solution (though not necessarily a better one) is to put your script tag just before the closing body tag of the document.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1></h1>
<p></p>
<script src="script.js" type="text/javascript"></script> <!-- PUT IT HERE -->
</body>
</html>
I know this has been answered and it is an old post but wanted to share my experience. I was having the hardest time getting my code to load and was getting this error constantly. I had my javascript external page loading in the head section. Once I moved it to just before the body ended the function fired up right away.