• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to swap out div tags programmatically with JavaScript

 
Mike London
Ranch Hand
Posts: 1208
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a straight-forward way to, say, when the user clicks a nav button, to swap out the text within a div tag?

What I'm trying to do is to update the page the user visits, as he clicks various nav buttons, by swapping out just the part(s) of the page that change (the main content div, in this case) without having to create a separate page with the nav bar and all the other parts for each page.

So, for an example, say you have a "home page" and the user clicks the "Testimonials" link. In my case, much of the "home page" would be the same for each page -- the nav bar, footer, etc.. So, all I'd need to do is to somehow "swap in" the Testimonials text for the main div on the "home page".

I looked at jQuery but couldn't figure it out with the books I looked at, so I'm back to JavaScript.

Look forward to any suggestions or code samples.

Thanks.

-- Mike
 
Eric Pascarello
author
Rancher
Posts: 15385
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can have the code there and just change the visibility [display = "none|block"] or you can fetch the content from the server using Ajax.

Eric
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64959
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
jQuery would make this almost trivial.

For example, to load a div from a URL:

 
Mike London
Ranch Hand
Posts: 1208
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bear, but how would you do the same thing in JS? A major pain?

----------

Also, you're appending with your jQuery code, right? If that's the case, how would you "replace" the div's current contents?

Thanks.

- Mike
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64959
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, that is JavaScript. jQuery isn't a new language, just a JavaScript library.

And yes, doing Ajax "by hand" is many more lines of code. You can find examples all over the web.

I highly discourage doing Ajax without the benefit of a library. There are too many nuances and pitfalls, and life is just too short to screw with them.
 
Mike London
Ranch Hand
Posts: 1208
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bear.

I appreciate, as always, your reply.

Best,

-- Mike
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic