This sample show how to attach globally to events over dynamically created elements.
And how can data-*
attributes be used to customize behaviour.
Created
April 8, 2016 08:59
-
-
Save bcardiff/38bc4180308c5b5a12fa7e9d0f9fe942 to your computer and use it in GitHub Desktop.
sample-data-confirm
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title></title> | |
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script> | |
<script type="text/javascript"> | |
$(function() { | |
$(document).on("click", "a[data-confirm]", function(e){ | |
if (confirm($(this).data("confirm"))) { | |
return true; | |
} else { | |
e.preventDefault(); | |
} | |
}); | |
}) | |
function addLink() { | |
var link = $("<a>") | |
.attr("href", "https://google.com") | |
.attr("target", "_blank") | |
.attr("data-confirm", "Are you sure?") | |
.text("go to google (js created)"); | |
console.log(this); | |
$("body").append(link); | |
} | |
</script> | |
</head> | |
<body> | |
<a target="_blank" href="https://google.com"> | |
go to google | |
</a> | |
<br/> | |
<a target="_blank" href="https://google.com" data-confirm="Are you sure?"> | |
go to google (with confirm) | |
</a> | |
<br/> | |
<a target="_blank" href="https://google.com" data-confirm="Oh, really?"> | |
go to google (with confirm) | |
</a> | |
<br> | |
<button onclick="addLink()">add link</button> | |
<br> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment