Change Content or Include File Without Refreshing Page - javascript

I've a menu and a content div. Content div is not displaying. When user clicks a menu item, content div shows and page smooth scrolls to top of the content div. Here is my code:
<div id="content">
<div id="section1">
<a id="bir" href="#icerikBaslik">1</a> <!-- This -->
<a id="iki">2</a>
<a id="uc">3</a>
<a id="dort">4</a>
</div>
</div>
<div id="icerikDiv">
<h1 id="icerikBaslik">Deneme</h1>
<p>Random content</p>
</div>
When user clicks "a id 1, (commented by This)" #icerikDiv shows and page scrolls. With this jQuery methods:
$('html, body').animate({
scrollTop: $(selector).offset().top
}, 1000);
};
$(document).on('click', '#content a', function () {
$('#icerikDiv').show();
scrollToElement($(this).attr('href'));
});
So that's it for a menu item. Question is, I don't want to lose smooth scrolling and because of that I don't want page to be refreshed.
When user clicked another link, content of #icerikDiv must be changed. Page will still scroll to #icerikDiv but content will be different. This is what I want.
And if possible, I want to keep content datas in php files. Like "menu1.php", "menu2.php" etc.
When user clicks a link, can I include related php file into #icerikDiv without refreshing page?
I thought about:
Give every link a specific method
Inside them, show #menuXcontent and scroll to #menuXcontent
Write down all content in same page, display:none;
For example when clicked menu6 link, show #menu6content and scroll to it
But I didn't like this. I'm sure there is a better way.

You have two main options. One is like you describe, to include all of the content in a single page and show it as needed. This is a viable solution which is used quite often. The advantage is that once the page loads it is very responsive, as it does not need to get data from the server when you click a link. The disadvantage is that the initial page load will be much bigger. It would generally work well for sites where the individual sections were quite small.
The second option is to use ajax to get your content from the server without a page reload. Ajax can be used to get data or html from your server. If you have a php file which gives the output you want in html, you can use the .load convenience method:
$( "#icerikDiv" ).load( "menu1.php" );
This will get the data from menu1.php and put it in to #icerikDiv.
To avoid hardcoding the php file, we can use a data attribute so that the source is declared on each link -
HTML:
<a id="bir" href="#icerikBaslik" data-content="menu-1.php">1</a>
Javascript:
$(document).ready(function() {
$('#content a').click(function () {
$( "#icerikDiv" ).load( $(this).data('content') );
$('#icerikDiv').show();
scrollToElement($(this).attr('href'));
});
});
It might make more sense to put the div target on the data attribute and use href for the source php - but it will work either way.

You can load content from a php file via ajax calls and append it to anywhere you want on the page using javascript.
Read up on ajax:
http://www.w3schools.com/ajax/
http://api.jquery.com/jquery.ajax/
A simple example would be:
$("#loadcontent").on("click", function(e){
$.ajax({
type: "get",
url: "loadcontent.php",
success: function(content){
$("#contentdiv").html(content);
}
});
});
This would change the content of #contentdiv into whatever is echoed from loadcontent.php.

Related

Load content inside div from another page with a url

I currently have Jquery tabs for different content on a page but this does not help me SEO wise as google and other places will not pick up this content.
I am looking for "tabs" but instead when you click on a link it loads that bit of information.
An example of this would be here http://www.gamespot.com/watch-dogs
You click on a "tab" say reviews and it loads that content along with a url of http://www.gamespot.com/watch-dogs/reviews/
I am looking to replicate something like this rather than using Jquery tabs.
Your help would be grand!
If you want the content to be picked up by search engines, it has to be in the original HTML. They won't run scripts that update the DOM on the client. So you need to do it in PHP:
<div>
<?php readfile("url"); ?>
</div>
However, if the URL is for a full web page, this is probably a bad idea. It will have its own <html>, <head>, and <body> tags, and these should appear only once on a page, not embedded inside another page.
<div id="myContent"></div>
load method:
$("#myContent").load("url to your content which you want to load", function(){
// things which you want to do with.
});
Try jQuery's load function:
$( "#element to put data in" ).load( "address", function() {
alert( "Load was performed." );
//what to do when done loading page
});
In order to make both search engines (which likely won't execute JQuery) and users (who might like dynamic elements) happy, you could do two solutions. You might have a link which when clicked goes to a brand new HTML page. Search engines will follow this link and see a whole separate page. Then, you might have a javascript within your page (or within the link's click event) that intercepts and overrides the original link's target and instead executes something like JQuery's $().load(). To reuse content you could have the target page be capable of loading both with and without a wrapper.
Target File:
<?php if(!isset($_GET['skipWrapper'])) { include('header.php'); } ?>
Here's the content that matters!
<?php if(!isset($_GET['skipWrapper'])) { include('footer.php'); } ?>
Source File:
<?php if(!isset($_GET['skipWrapper'])) { include('header.php'); } ?>
Here's the orginal content!
<a href="TargeFile.php" onclick="asyncLoad('TargeFile.php'); return false;">
<?php if(!isset($_GET['skipWrapper'])) { include('footer.php'); } ?>
Definition of asyncLoad:
function asyncLoad(url) { $('#targetElementId').load(url + '?skipWrapper=true'); }
However, it might be best to just stick with the traditional links rather than doing async tabs. Users get confused when the back button doesn't work or when common behaviors (like middle click to open a link in a new browser tab) no longer work.

Loading div inside html with jquery

I'm using jquery to load my website content once its fully loaded. That works great.
jquery code
function check() {
$("#content").load('items.html');
}
$(document).ready(function() {
check();
});
html
<div id="content">
</div>
Is there a way without refreshing the whole page to dynamically load html element (div) when user clicks on one of the items which were already loaded('items.html')?. On one click I want to remove already loaded 'items.html' inside #content div and load new div from any.html file.
So basically, I need to show more info for that particular item by dynamically replacing already loaded items.html and adding new div instead.
I managed to load new html page by adding anchor tags on every item, but it would be much better if I could load only one part(div) of a html file and not a whole page, that way I can write all items informations in only one html file, and then add those div's dynamically when user clicks on any item.
function check() {
$("#content").load('items.html #loadable'); // #ID to load
}
$('#loadCont').click(check);
main page example
page 2 example
You might also want to put this somewhere
$.ajaxSetup({ cache: false });
https://api.jquery.com/jquery.ajaxsetup/
As seen from the demo, .load() does already content-replacement, so no need to .empty() or .html('') beforehand.
Simple.Try to call the check() function on clicking of the element
$('element').click(function(){
check();
});

Data transition = Slide not working -dynamic list

I am new to Jquery mobile.
I am trying to get Sliding effect when i navigate to another page say # display2 from thie below code.
but i am not able to get slide effect.
If I remove the rel="external" i am able to slide but on the #display2(page whihc i would navigate to),the query string values are returned as null.
so if i put rel="external" the parameters are passed to #display2 but slide transition not working.
if i remove re="external" slide works but the querystring parameters are returned null.
can you please let me know is there a way where both of them work together.
('#display').on('pagebeforeshow', function () {
// $(this).find('[data-role=header] .ui-title').text(json.getLOBXMLResult[currentItem].FolderName);
$.ajax("AppstoreWS.svc/getLOBXML", {
beforeSend: function (xhr) {
$.mobile.showPageLoadingMsg();
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
contentType: 'application/json',
dataType: 'json',
type: 'GET',
error: function () {
//alert('Something awful happened');
},
success: function (data) {
result1 = data.getLOBXMLResult;
$('#categoryList').children().remove('li');
$.each(result1, function (index, output) {
$('#categoryList').append('<li>' + output.FolderName + '</li>');
});
$('#categoryList').listview('refresh');
}
});
});
Part 1 - why rel=external worked & other options
The reason why rel=external works with no transition is because this expects the browser to open an external page and therefore, disable ajax. To counter-effect this, you've got numerous options :
By using Single page template
You could make your two pages into a single page. This is called a single page template and your second page's reference would be #page2 (or any name you'd give as the ID). This is how it'd look like :
<div data-role="page" id="page1">
<!--Stuff in page 1-->
</div>
<div data-role="page" id="page2">
<!--page 2 stuff-->
</div>
Advantages
The DOM can leverage the power of ajax driven navigation.
This would make partial loading, script loading easy, as you'll need to refer all this only once.
Data-transfer between pages is very simple. You'll just have to store the data in you need in a global variable or in the data property of the #page2, and retrieve it in the pageinit or pageshow (or any event) of the second page.
Transitions, etc will work.
There will be no page refresh.
Disadvantages
If the HTML content of the two pages are large, it'll be difficult for maintenance.
By using rel=external
As you might have seen, rel=external can be used only when a page refresh is absolutely needed. Its upto the user's choice. If an a tag is marked with rel=external it means the browser will treat it as an external link, and will ignore jQuery Mobile's ajax navigation system.
By referring all the scripts of page 2 in page 1
Generally, to be able to use page transitions, you must use ajax system of navigation in jQM. So the general behaviour of ajax is as follows :
page1 will request for page2 in page2.html.
The <body> of page2.html alone is taken from page2.html.
The <head> section( which might contain your scripts, which might have your query-string logic) will be ignored.
So to change this, you can refer to page2's scripts in page1.html's head so that these scripts will be loaded and ready when jQM's ajax system pulls the body of page2.html.
<script src="jqm.js"></script>
<script src="page1.js"></script>
<!--page 2 scripts-->
<script src="page2.js"></script>
Advantages
Your transitions will be working properly.
The common scripts will not be referred to multiple times, hence much faster loading times.
Query strings will also work
Disadvantages
If the two pages have very little in common, you'll end up having unwanted scripts in your first page.
What if you have more than two pages? What if you have 10 pages? Will you refer to all 10 pages' scripts in page1. I dont think thats the way.
By referring to page2 scripts inside "data-role=page" section of page2.html (recommended)
This will bring the scripts along with the page when ajax brings it in. This will also work with query strings. This will look something like this :
<div data-role="page" id="page2">
<script src="page2.js"></script>
<!--- your html-->
</div>
Advantages
The scripts pertaining to a particular page are restricted to within that page.
Transitions will work.
Query strings will also work
Part 2 - alternative to query string
The reason I'm saying this because Query strings are archaic technology, because at that time, there was no way to store to data. They're also insecure because user can see the data you send over the URL. You must consider using something like localStorage. I'm not saying you must NOT use query strings. It's just that there are better options available for mobile data storage. See this link for more info about how you can use this localStorage. Also, see this for all the options you have. Now, looking at your query string :
platform=' + output.FolderName + '&sid=test
This could easily be made into an object. So in the click function of the anchor tag inside <li>,
$(document).on("click", "li a", function(e) {
//stop default action.
e.preventDefault();
//take the href; Im assuming its page2.html?platform=outputFolder&sid=test
var params = this.href.split("?");
//now params[0] = page2.html
//param[1] = platform=outputFolder&sid=test
//set this in localStorage
localStorage["page2params"] = param[1];
//change to page2.html
$.mobile.changePage("page2.html", { transition : slide });
})
Then, in the page2.html's pageinit method, you could retrieve it for your use :
//assuming you have a page with page2 as id in page2.html
$(document).on("pageinit", "#page2", function() {
var params = localStorage["page2params"];
//do anything you want with params.
});

How to realize screens / views with JavaScript / Jquery easily?

I'm sure I'm missing something pretty basic, but I have just started to get myself up to speed on jQuery and Javascript programming. Previously I was doing server side programming with PHP.
I'm now in the middle of creating a prototype for HTML5 webapp, where I would like to have different screens. Now with PHP that was pretty easy, I could just used server side templates like Smarty and be done with it.
However to make my app more webapp like, I would like to dynamically change between screens without having to reload the window.
I have looked into several options that might be anwsers to my question, but I'm not sure whether I'm on the right track.
I have checked for example JsRender, JsViews or even the pure jquery load command.
But what I'm not sure is whether these things would allow me to have something like this:
HEADER_PART
MAIN_CONTENT
FOOTER_PART (also contains links to common JS files that I use)
I would like to dynamically update the MAIN_CONTENT part. Currently my application is only one page, and all my custom logic that belongs to that page is in one JS file. In this JS file, I use a simple $(function() { ... to load my page, so whenever it gets loaded, parts of my page get updated asyncronously. This is fine, since all my blocks in this certain page would have to be loaded when that one page gets loaded.
But what if I have a link, like main.html#otherscreen, and when I click that screen, I would like to change my MAIN_CONTENT and also run another page load specific JS that handles blocks on that other screen, not the first page?
I know I could still use probably server side templating and load my pages using AJAX requrests, but again, not sure whether that is the right approach.
Could you please enlighten me? :)
Thanks & best regards,
Bence
Check out jQuery.load(). Using this function you can dynamically load content into a div on the page, which is what I think you want to do. Just find the div on the page you want to load content into and call
$('#mydiv').load(url, data, function(response){
//do something once it's done.
});
Per your comments...
This is actually very easy. .load() should replace the content in the div (I think. If not, just call .empty() first). Of course you could get fancy and add effects, like
function changePages(url) {
$('#mydiv').fadeOut('fast', function() {
$(this).load(url, function(response){
$('#mydiv').fadeIn('fast');
});
});
}
To handle things like the hash in the URL, in your click event you have to make sure you first call e.preventDefault():
$('#mylink').click(function(e){
e.preventDefault(); //e is a jquery event object
var link = $(this);
var hash = link.attr('href'); // get the hashtag if the href is '#something'
changePages(someUrl + hash);
});
For dynamic loading of data into the page without changing your header and footer you should use jQuery's AJAX function. It allows you to post requests to the server and receive data back without reloading the page. A simple example would be something like:
<html>
<head>
<title>Example</title>
<!-- Assuming jQuery is already referenced -->
<script type="text/javascript">
$('span.buttonish').click(function(){
$.ajax({
// The URL can be a file or a PHP script of your choosing
// it can also be pure HTML without the <html> tags as they
// are already in your file
url: 'path/to/the/file/that/return/data',
success: function(receivedData) {
// The received data is the content of the file or the return
// data of the script and you can use it as you would with any data
$('#content').html(receivedData);
}
});
});
</script>
</head>
<body>
<div id="header">
<!-- Something -->
</div>
<div id="content">
<span class="buttonish">Click me to change the text... </span>
</div>
</div id="footer">
<!-- Something -->
</div>
</body>
<html>

Link in one div, trying to load content in a seperate div

I am using jQuery to make a website, and I want to be able to have my navigation in a separate div from my content. Also, I want to be able to have a sort of tabbed navigation system such that I can click a link in the navigation and it will load the content into the main content div. Basically, I want to do this so that I can just maintain one page with all the content, rather than a bunch of pages for each section. I have included a picture that will hopefully make my question much more clear (right click and "viw image", it's too small on this page):
example http://img402.imageshack.us/img402/1733/examplew.jpg
$('#navlink').click(function() {
$("#maindiv").load("/url.html");
return false;
});
I would encourage you to use event delegation. For instance we can use the .on method to attach a single event to the navigation pane that will listen for clicks on links:
$("#navigation").on("click", "a", function(e){
e.preventDefault();
$("#content").load( $(this).prop("href") );
});
Which works with the following markup:
<div id="navigation">
Home
Gallery
</div>
<div id="content"><!-- content will load here --></div>
Considering that you want one page with all of the content, you could simple hide all but one main div with css, and then use javascript/jQuery to show one div when a tab is clicked, and hide all of the other (main divs).
Have your navigation links change the html of your center div
<a href="#" onclick="$('#centerDiv').html('your content');">Click me<a>
if you want it to be more dynamic use ajax to load it.
and if you want to get a bit more fancy try out the Tab widget
This calls for the jQuery load() function! Go to http://remysharp.com/jquery-api/ and search for 'load' -- you just need to target the div.
By the way, this is sort of an alternative to frames or server-side includes. The only bad thing about this approach is that Search Engines won't be able to follow your links.
Using ajax with jQuery its pretty simple and totally controllable:
$('#navlink').click(function() {
$.ajax({
type: "GET",
url: 'URL_OF_THE_RESOURCE',
//(maybe you can hold this in the href attr of the anchor tag)
//in that case you can use $(this).attr('href');
dataType: "text/html", //spectating HTML back from the server
timeout: 8000, //Wait 8 second for the response
error: function() {
alert('ERROR');//case of server error or timeout give a feedback to the user
}, //end error
success: function(html) {
$('#mainDiv').html(html); //Replace the content with the new HTML
} //end succes
}); //end ajax
return false;
}); //end click
Instead of usign an ID, you could use a dummy class (like "navlink") on all those navlinks, so instead of referencing the selector to the ID, reference it to the class like:
$('.navlink').click(function(){
...
and the url parameter will be:
url: $(this).attr('href'),
That way you just set this once and all the links will get the functionality and still give support to users that don't have JS active.

Categories

Resources