Well, it’s about time but I’ve finally taken the plunge and wrote my first jQuery plugin. I’ll admit, the decision wasn’t voluntary but a scenario on a recent project required a specific function that I couldn’t find had been previously catered for so I decided to kill two birds with one stone; complete the project and learn about the construction of jQuery plugins whilst putting it online for other people to use should they find themselves in a similar situation.
The requirement was to be able to swap two divs smoothly. Not just swap the contents of the divs in question, that was too easy, but to physically move the divs. One div to where the second div was positioned and vice versa, making the animation visible to the user to emphasise the movement.
After reading a few tutorials and a bit of debugging I had done it. The results of which can be seen below:
View a Demonstration
Installation
If you’d like to incorporate the Swapsies plugin into your own site, I have included a simple step-by-step below on how to do so:
1) Download the jQuery library here
2) Download the Swapsies plugin here
3) Include the scripts in your HTML like so, changing the paths to match where the JS files are located:
<script src="/js/jquery.js" type="text/javascript"></script>
<script src="/js/jquery-swapsies.js" type="text/javascript"></script>
4) Create the two divs you would like to swap, plus a trigger that will activate the swapping animation:
<div id="div_1">THIS IS DIV 1</div>
<div id="div_2">THIS IS DIV 2</div>
<a href="javascript://" class="go-swap">Go Swap!</a>
The HTML explained:
Div 1 (#div_1) – The first div on our page. This is one of the divs that will be swapped
Div 2 (#div_2) – The second div on our page. The other div that will be swapped
The trigger (.go-swap) – When clicked the swapping will commence. In our case this is a link but can be an image, a button or anything else you desire.
5) The final Javascript to bring our page to life:
$(document).ready(function() {
$(".go-swap").click(function() {
$("#div_1").swap({
target: "div_2", // Mandatory. The ID of the element we want to swap with
opacity: "0.5", // Optional. If set will give the swapping elements a translucent effect while in motion
speed: 1000, // Optional. The time taken in milliseconds for the animation to occur
callback: function() { // Optional. Callback function once the swap is complete
alert("Swap Complete");
}
});
});
});
Well there we have it. I hope that wasn’t too painful for you. If you have any questions with regards to integrating it into your site or have any suggestions on how the plugin could be improved simply leave a comment below.