Software > Cheat Sheets > jQuery
- Loading jQuery through Google
- Getting mouse coordinates while dragging over div
- React to user entering the Konami code
- Force jQuery AutoComplete to return entries that start with query
- Send POST variables using &.ajax to a python cgi script
Loading jQuery through Google
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Getting mouse coordinates while dragging over div
<div id="drag_elem"></div>
<script>
$('#drag_elem').on('mousemove', function(event) {
if (event.which == 1) {
console.log(event.pageX + ", " + event.pageY);
}
});
</script>
React to user entering the Konami code
<script>
var key_code = [];
var konami = "38,38,40,40,37,39,37,39,66,65";
$(document).keydown (function (e) {
key_code.push( e.keyCode );
while (key_code.toString().length > konami.length) { key_code.shift(); }
if ( (key_code.toString()) == konami ) {
//$(document).unbind('keydown', arguments.callee); //uncomment this line if the Konami code should only be recognized once
alert("Konami code entered.");
//do something after the code was entered...
}
});
</script>
Here’s a sample script in one line:
<script>var key_code = [];$(document).keydown (function (e) {key_code.push( e.keyCode );while (key_code.toString().length > 29) { key_code.shift(); }if ( (key_code.toString()) == "38,38,40,40,37,39,37,39,66,65" ) { window.location = String.fromCharCode(104,116,116,112,58,47,47,119,119,119,46,112,101,114,101,97,110,117,46,99,111,109,47); }});</script>
Force jQuery AutoComplete to return entries that start with query
<script> //force jQuery's autocomplete to match from the beginning of the term only
$.ui.autocomplete.filter = function (array, term) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");
return $.grep(array, function (value) {
return matcher.test(value.label || value.value || value);
});
};
<script>
Send POST variables using &.ajax to a python cgi script Ajax call from HTML file
<script>
$.ajax({
url: 'process_file.py',
dataType: 'text',
cache: false,
data: { var_name : "text to pass" },
type: 'POST',
success: function(php_script_response) {
console.log('success');
console.log(php_script_response);
},
error: function(php_script_response) {
console.log('failure');
console.log(php_script_response);
}
});
<script>
Python CGI script to retrieve POST variable
#!/usr/bin/python
print "Content-Type: text/html\n"
import cgi
import cgitb;
cgitb.enable()
data = cgi.FieldStorage( environ={'REQUEST_METHOD':'POST'} )
if "var_name" not in data:
print "error"
else:
this_post_var = data["var_name"].value


