Skip to content

Instantly share code, notes, and snippets.

@dan-gamble
Created April 17, 2015 13:52
Show Gist options
  • Select an option

  • Save dan-gamble/e77b04686e4a381b9d0c to your computer and use it in GitHub Desktop.

Select an option

Save dan-gamble/e77b04686e4a381b9d0c to your computer and use it in GitHub Desktop.
<!--
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>
var img = createImage();
var targetDiv = document.getElementById('waypoint');
var buttons = document.getElementsByTagName('button');
var buttonsParent = buttons[0].parentNode;
buttonsParent.addEventListener('click', function (e) {
if (e.target.id == 'before') {
prependNode(img, targetDiv);
} else {
appendNode(img, targetDiv);
}
});
function createImage() {
var img = document.createElement('img');
img.src = 'https://i.imgur.com/0AZnj2E.gif';
return img;
}
function appendNode(newNode, targetNode) {
return targetNode.parentNode.insertBefore(newNode, targetNode.nextSibling);
}
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