Moving page elements using jQuery
Wednesday 23 November 2011
I'm currently working on a project to convert a web site to a responsive design. On mobile devices I want the primary page content to appear near the top of the page with other (less important) content below.
For the site in question I can get so far using CSS to reposition page elements. However, when CSS won't do the job I've used jQuery to detect whether a mobile device is being used and rearrange page elements to their desired locations.
Here is an example of how to reposition page elements using jQuery.
Firstly, add the following HTML inside your web page's BODY tag to create some sample page elements.
<div id="element-a"><h2>Element A</h2></div> <div id="element-b"><h2>Element B</h2></div> <div id="element-c"><h2>Element C</h2></div>
Now add the following JavaScript before the closing BODY tag.
<!-- import jQuery --->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script>
// when the page has loaded run the following code
$(document).ready(function(){
// target mobile devices
if($(document).width()<=480) {
// remove element A and insert it before element B
$('#element-a').remove().insertAfter('#element-b');
// remove element C and insert it before element A
$('#element-c').remove().insertBefore('#element-b');
}
});
</script>
If you view the page in a web browser with a width less than 480 pixels you'll see that element C appears above element B and element A appears below element B.
Tags
jQuery (7) CSS (3) Responsive Design (3)Share
Comments
Be the first to add a comment!