Created
April 17, 2015 13:51
-
-
Save dan-gamble/24d6c99c28a487b3c8be to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!-- | |
| Below we have one main div with the id 'waypoint' | |
| and 2 buttons with the id's 'before' and 'after' | |
| the aim of this is when you click the respective buttons | |
| this image 'https://i.imgur.com/0AZnj2E.gif' will appear before | |
| and after the waypoint div as marked out by comments | |
| Code goes in the script tags below | |
| --> | |
| <!DOCTYPE html> | |
| <html> | |
| <body> | |
| <!--Where the before image will appear--> | |
| <div id="waypoint"> | |
| <p>Hello world!</p> | |
| </div> | |
| <!--Where the after image will appear--> | |
| <div> | |
| <button id="before">Before</button> | |
| <button id="after">After</button> | |
| </div> | |
| <script> | |
| // The image we will be using | |
| var img = createImage(); | |
| // The div we will be moving our image around | |
| var targetDiv = document.getElementById('waypoint'); | |
| // Our control buttons | |
| var buttons = document.getElementsByTagName('button'); | |
| // Get our buttons parent so we can assign the click event to it | |
| var buttonsParent = buttons[0].parentNode; | |
| // Assign the event listener to the parent so it's a little better performance | |
| // wise (1 event vs 2 or more) and hopefully makes it a bit more modular | |
| // in case we wanted to add more buttons in the future | |
| buttonsParent.addEventListener('click', function (e) { | |
| if (e.target.id == 'before') { | |
| prependNode(img, targetDiv); | |
| } else { | |
| appendNode(img, targetDiv); | |
| } | |
| }); | |
| // Create our image that we will throw about | |
| function createImage() { | |
| // Create a new image node | |
| var img = document.createElement('img'); | |
| img.src = 'https://i.imgur.com/0AZnj2E.gif'; | |
| return img; | |
| } | |
| // Append a node to a target node | |
| function appendNode(newNode, targetNode) { | |
| return targetNode.parentNode.insertBefore(newNode, targetNode.nextSibling); | |
| } | |
| // Prepend a node to a target node | |
| function prependNode(newNode, targetNode) { | |
| return targetNode.parentNode.insertBefore(newNode, targetNode); | |
| } | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment