Skip to content

Instantly share code, notes, and snippets.

@stonehippo
Created January 12, 2013 03:18
Show Gist options
  • Save stonehippo/4515873 to your computer and use it in GitHub Desktop.
Save stonehippo/4515873 to your computer and use it in GitHub Desktop.
A simple example of jQuery event binding (in this case, click events on some divs). For my brother.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<style>
div[class^='block-'] {
height: 10em;
width: 10em;
position: absolute;
-webkit-box-shadow: 1px 1px 4px rgba(0,0,0,0.25);
}
.block-a {
background-color: green;
}
.block-b {
background-color: blue;
}
.block-c {
background-color: orange;
}
.faded {
opacity: 0.5;
z-index: -1;
}
</style>
</head>
<body>
<div class="block-a"></div>
<div class="block-a"></div>
<div class="block-a"></div>
<div class="block-a"></div>
<div class="block-b"></div>
<div class="block-c"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
// At startup (really the JQuery DOM-ready event) bind all of the event handlers
$(function() {
// get a reference to all of the blocks, so we can do stuff to them
var blocks = $('div[class^=block-]')
// distrubute the blocks to random positions
blocks.each(function() {
var x = Math.random() * 320,
y = Math.random() * 320
$(this).css({top: x, left: y})
})
// bind an event handler to all blocks
blocks.on('click', function(e) {
console.log('clicked a block.', ['block class was', $(this).attr('class')].join(' '))
// all boxes remove the faded class
// this has the effect of making the orange box a reset, since we won't bind anything else to
blocks.removeClass('faded')
})
// bind an event handler to our blue blocks only
$('.block-b').on('click', function(e) {
// make the green blocks fade into the background
$('.block-a').addClass('faded')
})
// bind another event handler to our green blocks
$('.block-a').on('click', function(e) {
$('.block-b').addClass('faded')
})
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment