Skip to content

Instantly share code, notes, and snippets.

@bcardiff
Created April 8, 2016 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcardiff/38bc4180308c5b5a12fa7e9d0f9fe942 to your computer and use it in GitHub Desktop.
Save bcardiff/38bc4180308c5b5a12fa7e9d0f9fe942 to your computer and use it in GitHub Desktop.
sample-data-confirm

This sample show how to attach globally to events over dynamically created elements. And how can data-* attributes be used to customize behaviour.

<!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