Pregunta

I am developing a website for mobile devices. The website has different pages. Some of the elements like header are common in every page. I do not want to duplicate the code. Is there any way to change only a part of the webpage not the whole. The elements in the header should not change when the transition from one page to the other happens.

I will appreciate any suggestion.

Regards

¿Fue útil?

Solución

You have a few options:

  • Use an iframe
  • Use Ajax
  • Use a templating system

The first 2 can be done relatively easy with Javascript/jQuery.

You will need to change the source of your iframe, as you click on a link, or, you can request the new content through ajax and replace the current content with the new content.

You can try something along these lines in jQuery using an iframe:

$("a").click(function(e){ 
  //In order to stop following the link, but call our own function
  e.preventDefault();

  //Get the URL of the link we clicked
  var new_content_link = $(this).attr("href"); 

  //Now set the new source of the iframe so the content reloads
  $("iframe").attr("src", new_content_link);
});

You will need some HTML to go with it:

<a href="/some_other_page.html">Some other page</a>
<iframe src="/current_page.html"></iframe>

Clicking the link will result in the iframe's source being replaced with "/some_other_page.html" and the contents of that HTML file will be loaded into your iframe.

Now trying this with Ajax, you'll need something along these lines:

$("a").click(function(e){ 
  //In order to stop following the link, but call our own function
  e.preventDefault();

  //Get the URL of the link we clicked
  var new_content_link = $(this).attr("href"); 

  //Request the content of the other page into our #content div:
  $("#content").load(new_content_link);
});

HTML that can go with this:

<a href="/some_other_page.html">Some other page</a>
<div id="content">Old content</div>

Click the link now, will call jQuery's load() function, which loads the contents of "/some_other_page.html" into the div#content.

If you need some information about templating systems, I'd suggest you go find a CMS, like Wordpress, or find yourself a framework to work in, like Laravel(PHP), CodeIgniter(PHP) or Express (node.js).

Goodluck!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top