Using appendTo and Load in click

jQuery newb and the first poster. Please be careful :-) I searched and cannot find the answer, but I'm sure there is a really simple solution.

Hope someone can help me. Here's what I'm trying to achieve: I have a number of tabs, and all but the first tab use the click function to load () the external page into the required div. The first tab will load the default content, not from an external file, but from the div already on the page, but further down the code for SEO reasons.

Clicking on any other tab loads the content from the external page into the div, but if you want to return to tab 1, the content is not available, since it was replaced by the contents from load (), that is, it was no longer in the DOM.

I suppose I could add a div to #temp before calling load (), and then add it back if link 1 was clicked, but should there be a more elegant solution?

Here is the code:

$(document).ready(function(){ // default tab1 content div appended to containing div OK $("#innerDiv1").appendTo("#outerDiv"); // tab2 link loads page2.html OK $("#link2").click(function(){ $("#outerDiv").load("page2.html"); }); // This doesn't work as it no longer in the DOM after #link2 clicked. $("#link1").click(function(){ $("#innerDiv1").appendTo("#outerDiv"); }); }); 

Any thoughts and answers were greatly appreciated.

Thanks in advance M

+4
source share
4 answers

Change the click #link1 to this:

 $("#link1").click(function() { $("#outerDiv").load('originalurl.html #innerDiv1'); }); 

this uses AJAX to load the start page, but only grabs the '# innerDiv1' section and replaces its contents #outerdiv . You will need to replace originalurl.html with your actual url ... maybe you can use location.href if you don't update this for bookmarking?

0
source

Most tab systems have a separate content container for each tab. Clicking on a tab hides visible content and displays hidden content associated with the current tab. It seems like all you do is destroy the html every time, which makes a lot more coding effort.

More robust tab systems like jQuerUI have integrated ajax options to simplify a lot of what you need. Since you are saying that you are new to this ... it would be useful to use solutions that also provide excellent support like jQueryUI

http://jqueryui.com/demos/tabs/

+2
source

You can try the jQuery tabs widget: http://jqueryui.com/demos/tabs/

It should simplify the creation of a tabbed interface, and you can simply include all the contents at once or load via AJAX, this is a flexible widget.

+1
source

I would save the contents of each #outerDiv for each tab somewhere. You can use jQuery data method . Or you create a .outerDiv for each tab, load the content for the first time, and then show only the .outerDiv of the active tab and hide the rest.

0
source

Source: https://habr.com/ru/post/1400060/


All Articles