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

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.

Related

jQuery calling div element that has been loaded by ajax, or inserted via html() method

It's my first post on stackoverflow. I've searched similiar questions here and found a couple of answers but couldn't really find a solution to this particular problem that would help me.
I have a webpage which loads main contents by ajax. Simply like this:
function loadContent(content) {
if(localStorage.content != content) {
$("#content #content_loading").css("display", "block");
}
var userID = Cookies.get("UserID");
$.ajax({
url: '../game/data/load_content.php',
type: 'post',
data : { ID : userID, Content : content },
success: function(response) {
$("#content #content_loading").css("display", "none");
$("#content #import").html(response);
localStorage.content = content;
$("#header").html("<div class='header_text'>"+content+"</div>");
}
}); }
It loads other ajax functions, html and css. Since I have thousands and thousands lines of code simple things get trickier. Now I simply want to create an universal 'close' button for popup windows. All of the popup windows are in a box, and the close button is inside the box header. Now I want to close all popup windows with a single function:
$('.close').click(function() {
$(this).parent().parent().fadeOut();
});
This simply selects the parent of the close element, which is header and then parent of that parent which is the whole box. One of the popup functions looks like this:
function showPopup(header, content) {
$("#popup_header").html(header+"<div class='close'></div>");
$("#popup_content").html(content);
$("#popup").fadeIn(300);
}
This function is included in the main document (<script src="script"></script>).
Then the other popup is directly loaded upon loadContent(content) function, so it's loaded with ajax call. And it's simply HTML that looks like this:
<div id="nearby_players">
<div class="header">PLAYERS NEARBY <div class="close"></div></div>
<ul> </ul>
</div>
Now if I insert the 'close' function upon click in the document that ajax is loading it will work. And if I change the loadPopup() function to this:
function showPopup(header, content) {
$("#popup_header").html(header+"<div class='close'></div>");
$("#popup_content").html(content);
$("#popup").fadeIn(300);
$(".close").click(function() {
$(this).parent().parent().fadeOut();
});
}
It works too. But what I want to do is to create a single click function attached to the main document that will close all the possible popups that are being loaded on the webpage or already are on the webpage. I thought it was a problem since 'close' element was an ID not a class. And since it should be unique I've changed it to class. So my question is. How do I refer to all of the elements with class 'close' whether they are being loaded with ajax, and then within that ajax they get loaded again with another ajax and so on. And also the popups that are already inserted into document when the webpage gets loaded?
How do I add these elements to the DOM so jQuery actually finds it?
Regards,
Hazes!
You create elements dynamically, which means that events are not attached to them.
Please read how to attach events to dynamically created elements: http://api.jquery.com/live/

Loading a hyperlink opened in a div - in the same div

Following on my from my previous question here:
How to show a page by default on page load
I'm basically using jQuery to load links in a div - this works perfectly. However, what I want to now achieve, is when one of the pages (opened in the div) has a hyperlink, how can I open the hyperlink in the same div the page sits in now?
Let's say I have a menu:
Home | Service | About
If you click service - it loads the page inside a div - awesome.
But let's say service has a hyperlink to another page (on the same domain/setup) - currently using my code referenced in the question above, the link just opens in a new tab... This isn't the behaviour I want.
Here is the code:
$('[data-target]').click( function (e) {
$.get($(this).attr('href'), function(data){
$('#halloffame').empty();
$(data).find(".partner_body").appendTo("#halloffame");
});
e.preventDefault(); // prevent anchor from changing window.location
});
$.get( "pages/accounting-software/", function( data ) {
$('#halloffame').empty();
$(data).find(".partner_body").appendTo("#halloffame");
});
This lets me open hyper links in the div "halloffame". But it doesn't control the links in the pages - even if I use the same code on the master page:
<a data-target="#halloffame" href="pages/returns/">
If anyone can point me to where I'm going wrong, I would appreciate it :)
Have an awesome Friday, folks!
Your event listener is bound the the currently existing DOM, when you add new elements(from your ajax call) you need to either bind your event listener to the new elements aswell or use deferred event handling(eg jQuerys on).
See this answer for more details

Limited with JavaScript onCLick() when making AJAX call

I am working on an existing project and heavily using jQuery AJAX calls. Existing pages have three different sections header, left menu and main content. Implemented with Spring MVC it is updating whole page whenever view is returned from Spring controller.
Now since I am working with one of the menu item but having tab content I am using jQuery to manipulate data within tabs using jQuery. While doing so whenever I have to work with hyperlink I can't use <a> tag since return from link will replace whole page . So I am always limited to use onClick() even ton the link and do AJAX call then put response back in window using jQuery.
Details
<script>
$.ajax({
type: ...,
url: ...,
success: function(response) {
$('#tab1-content').empty().html(response);
}
});
</script>
So my question is - Is there any other way so that I can use href properties of <a> tag and update window with response view?
I am not sure if I understood you correctly. Could you try something like this:
Details
<script>
$('a').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
loadDetail(href);
});
function loadDetail(url) {
alert("Load from: " + url);
// Ajax call
}
</script>
Fiddle
You can prevent default behaviour of tag just return false from your function.
See this fiddle http://jsfiddle.net/s8mpwokt/
Or just like in Michael answer attach event from javascript so you'll get event instance in your callback function with preventDefault() and stopPropagation().

Change Content or Include File Without Refreshing Page

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.

Displaying different content on the same panel using Javascript.

I have a list of anchor tags on a website. How can I change the content of a panel depending on which tag is clicked. I don't want the page to change. I am guessing I will need to use JQuery but I don't want to use tabs. Please help. Thank you.
When Anchor Clicked Trigger this to pull new panel, test.php would do the work.
then just insert the returned html.
You will have to include jQuery library
$.post("test.php", { PanelNum: Num},
function(data) {
$("#panel").html(data)
});
$(document).ready(function() {
$('a').click(function(event) {
event.preventDefault();
**code to change panel content, whether it be an
ajax request or simple $('selector').html()**
});
});

Categories

Resources