What is the best way to change 'views' with Javascript? - javascript

For example, I have profile page and select with 'About', 'Photos', 'Videos' section etc., and I don't want to refresh page each time I change section, I want just to change the content of container with Javascript. Sure it wouldn't be handy to write markup of pages in Javascript file, and my idea would be to write div's of each view and display only one of them:
<div id="about>About content</div>
<div id="photos" style="display: none;">Photos content</div>
However, I think there are better ways to do it, because I don't like keeping hidden views on the page. Also in most cases content in views should be generated by script, so it's looks like job for a template engine, but I'm not sure there are such in Javascript.
So what would be the best way to implement this in Javascript. I hope my idea is clear. Thanks in advance!

Try use mustache it is a template engine for javascript.
Also, you can use AngularJS templates (dynamically loaded into page on demand)
It is very easy to use. (However contains other things you might not want.. but should want ;) )

Use jQuery to fetch for the views whenever the user clicks on a link.
For example, bind the click event:
$('#clickToSeePhotos').click(function(){
$('#photosContainer').load('pathTo/photos.html');
});
$('#clickToSeeAbout').click(function(){
$('#aboutContainer').load('pathTo/about.html');
});
Here is the html:
<a id="clickToSeePhotos" href="#">Photos<a/>
<div id="photosContainer"></div>
<a id="clickToSeeAbout" href="#">About<a/>
<div id="aboutContainer"></div>
Here is a link to jQuery's page where they provide more info and examples for load
http://api.jquery.com/load/
You may download the jQuery library and use it on your server. However, as #Cybrix suggests you can also point to the library hosted by Google. See this link. At the end this could improve performance for your users.

Related

HTML Make code run independently from the rest of the page...iframe?

This is a little hard to explain. I'm creating a webpage that shows how other webpages will render in the browser. Here's a simplified version of the problem I'm having...
<div id="test">This is an example of page 1</div>
<div id="test">This is an example of page 2</div>
As you can see, both divs have the same ID. I can't change the ID in my situation and it's causing problems. I'm having various other CSS and javascript problems also. Each section of code is conflicting with the other. So, I was looking for a way to have a section render independently of everything else. One way to do it would be to create an iframe for each section of code. But that would require me to create a separate webpage for each section, right? Or, is there a way for an iframe to work just by entering code into it, rather than a URL.
You can only have one id per element in an HTML document. So each div must have a different id, otherwise you will run into problems. If multiple elements need to have the same name, you can use classes <div class="test" id="unique-id"></div> and then <div class="test" id="another-id"></div>.
To answer your question with regards to iframes, yes, you need a separate page for each iframe. It is not possible to write code within the iframe tags to execute separately. See the iframe spec.
Edit: After reading the iframe spec myself, it appears you can use the srcdoc attribute to overwrite what is in the src attribute, but it looks like this isn't entirely accepted across browsers. MDN has more information about the attribute.

on click href, how to create new html page and write html dynamic in to page using jQuery?

I am trying to implement web application for sales. So in that i would like to generate dynamic html pages on fly by clicking on a product.
<a href="/products/34567.html">
<img src="leather1.png" alt="Leather Bag" width="82" height="82">
</a>
when i click on leather1.png , i should redirect to 34567.html.
But 34567 html page will not be present in my source. On click image i want to create new html page naming 34567.html and write html content in to the page using jQuery.
Can any one help me on how to approach to achieve this..
Your immediate response is highly appreciated!
Thanks.
i think you arelooking for this:
check out this paper: http://www.htmlgoodies.com/beyond/javascript/article.php/3776371
goodluck!
Based on your comments, what you want is an AJAX call. You'd want to have an onclick action on the anchors that would trigger an AJAX request, with a callback that knew how to render the result - it could replace the document object's html. Then for useability the action should probably display a loading screen. Finally, the action should return false so the link isn't followed.
Key point: if an onclick operation on an anchor tag returns false, the link is not followed by the browser.
I would hasten to add though, having the href of a link simply not work is a bit of an anti-pattern. Your HTML is telling the browser there's a related document at /products/34567.html ... SEO will not find your product 'pages'. AJAX is all well and dandy, but this isn't the best use of it. best if that link really worked, and the AJAX was just an optional step. Web crawlers don't usually run JS and won't find your products - and if you want them to sell, you want google to find them!
Hope that makes sense!

How do I use small html markup repeatedly?

I am working on standalone JavaScript application which is being coded in HTML 5.
It has almost 50-60 html pages including repetitive markup such as header, footer and nav.
But if I have to make change in header then I have to make changes in 56-60 pages.
Is there any solution to use reusable html markup so if I did changes in one page it will reflect to other pages?
I can't even use php.
Prepare one javascript function. Write your html elements through javascript or jquery function. run it in page load event. and call the function in html by div.
Put this javascript function in separate .js file. And call this js file in wherever you want. And just place the div wherever you want in the html page.
See this jsfiddle DEMO
I Hope this demo will useful to you in this situation.
If you are using HTML (.html) pages and do not have Server-Side-Includes option then you can use a JavaScript template (which is not too difficult).
Second option : use of iframe.
Write the whole javascript code in common_layout.js
Add every statement using id of that div and add this file with main layout.
$( document ).ready(function() {
$('#header').html('<b>Header</b><ul><li>First Link</li><li>Second Link</li></ul> ');
});
UPDATE: One of my favorite post from TutsPlus : Best practices when working with JS Templates
If you are just started with this application. You can think of using client side java script frameworks like - AngularJS. It would be lot easier to maintain the code and solve such trivial issues.
You can use object tag like this:
<object name="header" type="text/html" data="header.html"></object>

other than ng-view page loading

I am using a master page having navigation and ng-view on it, partial pages loading successfully under ng-view and with navigation of master page , but I require to load some isolated page like login.html page but not under ng-view and without master page content during route.
I am new on angular and not sure how to do this, login page loaded every time under ng-view.
Please suggest me any way to do this.
Thanks in advanced.
ng-include is your friend. see doc
here is simple way, but you should go to doc and see that there are extra options as to what can be done onload and if you want to autoscroll or do some kind of animation.
<div ng-include="'somefile.html'">
</div>
The one extra note is that ng-include is given an expression so if you have a static reference you need the extra quotes.
One of the great things about Angular is it is very flexible. Ultimately it will depend on your app and how you work. I'm not exactly certain what you are trying to accomplish but, it sounds like a job for the ngInclude directive as Dan mentioned.
You mention a login.html that excludes navigational and other main page content. Using a modal may be a viable alternative interface decision.
If you have everything built and you only want to hide part of the DOM and be done with it then, nghide or ngShow may be the quickest solution.
If there is a lot of stuff on your index.html you may want to separate those things into partials other than the ones connected directly to your routes, and use ng-include="'path/to/partial.html'" to include them. (The "''" are intentional as it likes a string.) Read the docs and experiment with the plunkr. You can do a lot of cool things with ngInclude, especially if you pay attention to its context.
If you combine the ngInclude directive with ng-switch-when, you could put together something like:
<div ng-switch="routeAction">
<div ng-switch-when="extpage" ng-include="'extraneous.content.html'"></div>
<div ng-switch-when="login" ng-include="'login.partial.html'"></div>
<div ng-switch-default ng-include="'default.tpl.html'"></div>
</div>
Where routeAction is tied to your controler which, is tied to your $route or $location.. depending on how you have things set up.

What is the best way to organize unobtrusive JavaScript across multiple pages?

I love jQuery but am running into a problem with larger site and multiple pages. My problem is that each page has unique requirements and I need to know the best way to tell jQuery which pages to activate certain things. For example, some forms need the Validator plug-in and some don't, some tables use DataTables plug-in and some don't, etc.
Now I guess I could build complex logic (switch statements) into my application JavaScript file that fire different actions depending on what page they are on, but that just seems smelly. What is the Best Practice here?
UPDATE: There have been lots of good ideas on this question but not quite what I'm looking for. Let me rephrase the question in a more general way.
Currently I am using Rails and its Prototype helpers to build my AJAX components, but I want to move to UJS. How do I tell jQuery which links/buttons to make AJAX and which to avoid? And, given that I can differentiate the that are supposed to have AJAX, how do I give each link its own parameters (method, update, etc.) like I could with the helpers?
I mean besides building a huge page of specific jQuery selectors targeting each individual link/button. :)
jQuery plugins usually are activated upon DOM elements, for example:
$("#element").myPlugin();
If the element doesn't exist on the page, plugins usually behave safely by not activating the plugin.
If your plugin doesn't follow this structure I would suggest doing something like this:
if($("#element").length) $("#element").myPlugin();
A good practice is to have code that is required by all pages in one file and to have specific javascript files for pages that require specific functionality. It sounds as though this is what you are doing anyway, so we have a good basis to build upon.
There are numerous ways in which you could build in what pages need what files, but remember that in normal circumstances, javascript files are cached by the browser such that those files need only downloading once.
In light of this comment
Yes, but what if you have multiple
pages with the same DOM elements? For
example, my validator() plugin is set
up like $('form').validate(), but
sometimes I don't want it to act on
all the forms on the page, only some
of them. What do I do in this case?
I suggest coming up with a convention by which to label elements common across pages that require certain jQuery plugins "attached" to them. For example, if you have a <form> element on a number of different pages that requires a validator() plugin, but there is more than one <form> element on any one particular page (and not all <form> elements should have the validator() plugin), then I suggest using a CSS class to distinguish the <form> elements that do need the plugin.
<!-- HTML -->
<!-- need to apply plugin to this -->
<form class="validator"> ... </form>
<!-- but not to this -->
<form> ... </form>
<script type="text/javascript">
// jQuery Code (in a separate file)
$(function() {
$('form.validator').validator();
});
</script>
That way, the plugin will be applied only to those <form> elements matching the selector.
EDIT:
I'm not sure how the helpers in rails work, but you can pass data to an event handler in jQuery using the data parameter of the bind() method for any data that is not directly part of an <a> element itself (such as an attribute like href). If some of the links require AJAX, then it may make sense to label those with a CSS class and store the URL in the href for the element. Then in your jQuery code that can be used on any pages that have links that make requests through AJAX, you could do something like
<a class="ajax-link" href="/get/someData.php">Data retrieved through AJAX</a>
Standard link with no AJAX
<script type="text/javascript">
$('a.ajax-link').bind('click',ajaxRequest);
function ajaxRequest(e) {
e.preventDefault();
$.get(e.target.href, function(data) {
$('#loadDiv').html(data);
});
}
</script>
the link will work as per a normal link when a user has JavaScript disabled, but will make an AJAX request for data when JavaScript is enabled. I've used a named function here, ajaxRequest as it can make it easier to debug the script (and perhaps also reuse), but you could use an anonymous function if you prefer.
Found nice custom solution
http://topsecretproject.finitestatemachine.com/2010/04/how-to-organizing-javascript-in-ruby-on-rails/
One thing I always do is add an id to the body tag of each page, where the id is the name of the page (<body id="contact">). That makes both javascript and css selection very easy.
For example:
<!-- HTML -->
<!-- need to apply plugin to these forms -->
<form> ... </form> on the about.php page
<!-- but not to this -->
<form> ... </form> on the index.php page
<script type="text/javascript">
// jQuery Code (in a separate file)
$(function() {
$('body#about form').validator();
});
</script>
You could pass key value pairs to your main JavaScript module informing which plugins should be imported. This technique is used by scriptaculous.
<script type="text/javascript" src="scriptaculous.js?load=effects,dragdrop">
Another approach is to define in server side which media files are needed for each form/page, so the html can be rendered automatically with links to the scripts that are going to be used. Django has a good implementation of this technique:
class CalendarWidget(forms.TextInput):
class Media:
css = {
'all': ('pretty.css',)
}
js = ('animations.js', 'actions.js')

Categories

Resources