Anyway, the purpose of this post is to offer a brief code example that uses JQuery to manipulate the DOM of your website. I also provided some references that I used, so if you want to do some exploring just click away!
What you need:
- The JQuery framework for JavaScript
- Some knowledge of HTML, CSS and Javascript
- A web-server such as Apache or nginx
Summary:
This post will show a couple of quick 'Hello World' examples, followed by a quick overview of some interesting functions available in JQuery.Hello world: Example 1
The following code includes HTML comments to explain the code:
<html>
<head>
<title>jQuery Hello World</title>
<!-- Include the JQuery Library code... JQuery will not work without this -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<!-- Our JQuery function. This will search for #flag and inject the Hello world text -->
<script type="text/javascript">
$(document).ready(function(){
$("#flag").html("Hello World !! (display due to jQuery)");
});
</script>
<body>
<!-- Note that this is empty, but upon execution will contain text -->
<div id="flag">
</div>
</body>
</html>
Hello world: Example 2
This Hello World example differs slightly in that it now uses an alert box to display the text:
<html>
<head>
<title>jQuery Hello World</title>
<!-- Include the JQuery Library code... JQuery will not work without this -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<!-- Our JQuery function. This will output a text box on the click event -->
<script type="text/javascript">
$(document).ready(function(){
$("#cl").click(function(){
alert("HELLO WORLD!");
});
});
</script>
<body>
<button id="cl">Click Me</button>
</body>
</html>
Editing and manipulating JQuery elements
This code will output the size of any div element that is of the "change" class:
alert($("div.change p").size());
// This will count any <p> element within <div class="change"></div>
This will slide a <p class="first"> element up or down to hide/show it when called:
$("div.change p.first:hidden").slideDown("slow");
$("div.change p.first:visible").slideUp("slow");
This will instantly change the CSS code of any <em> element within <div class="change"></div>:
$("div.change em").css({color:"#993300", fontWeight:"bold"});
References:
- JQuery Hello World script from Rose India
- Example code from w3schools
- Live examples from the JQuery website
- A guide to getting started with JQuery
- Some tips from the JQuery website
- for element selection
- The whole JQuery API reference
No comments:
Post a Comment
Thanks for contributing!! Try to keep on topic and please avoid flame wars!!