I’m basically wondering if I can inter-mix JavaScript and jQuery any way I want, or are these more like two different worlds and I have to be careful when crossing boundaries. I strongly suspect it’s the latter case but don’t know how or where to respect boundaries. For example, in the following code of mine doesn’t work. (I suspect it stems from a lack of understanding why and where $(document).ready is necessary.) I read a bit about the .on method, but it doesn’t really answer my question.
When I run this code in Chrome it flashes stuff briefly and I don’t know why.
<html>
<head>
<title>prototype Day 1</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", (($(window).outerHeight() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
this.css("left", (($(window).outerWidth() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
return this;
}
$(document).ready(function() {
$("div#main").center(true);
});
function stubMethod () {
$("div#main").append("<p>stuff</p>");
}
</script>
</head>
<body>
<div id="main">
<div id="search">
<form method="get">
<label>Define:</label>
<input type="text" id=""></input>
<button onclick="stubMethod()">Go</button>
</form>
</div>
</div>
</body>
</html>
you should add event handlers via JS rather than use it on the elements themselves:
DEMO HERE
what was happening in your code was that when the button was called, the form is submitted, thus, your page moved away. even if the append took effect, you would not see it because the form was submitted.
also, if you placed
stubMethod()inside.ready(), it means that your function isn’t in the global scope anymore, andonClick="stubMethod()"won’t work anymore.