Monday, June 9, 2008

Change div content with jQuery

This is a quick tutorial for understanding the basics of jQuery.

Create a new HTML file with this code:
<html>
<head>
<title>jQuery test page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// javascript here (jQuery)
</script>
</head>
<body>
<--- HTML content here -->
</body>
</html>
Right now, the page will just load the jQuery library.

Lets get some HTML content first
<a id="changeText">Change my text</a>
<br />
<div id="textBox">This text will be changed to something else</div>

jQuery code
Now we will add some javascript so that the content of 'textBox' element changes to something else once you click on 'Change my text' link.
$(document).ready(function() {
$(
"#changeText").click(function() {
$(
"#textBox").html("My text is changed!");
});
});

As soon as your page is loaded in your browser, a function is declared so that whenever you click on the link (with 'changeText' id), the content of the 'textBox' element will be changed to 'My text is changed!'.

Final output:
<html>
<head>
<title>jQuery test page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function() {
$(
"#changeText").click(function() {
$(
"#textBox").html("My text is changed!");
});
});
</script>
</head>
<body>
<a id="changeText">Change my text</a>
<br />
<div id="textBox">This text will be changed to something else</div>
</body>
</html>

10 comments:

  1. was looking for this for long. thanks :D

    ReplyDelete
  2. jQuery rocks! thanks for taking your time and sharing your code :)

    ReplyDelete
  3. dude, cool and simple way to handle this task! thanks a lot, was looking for this...

    ReplyDelete
  4. Thanks a lot.
    I have a question, though. How can I change more div contents respectively? So I have more stuff with different id-s and I'd like to have them changed when I click on a menu item.

    ReplyDelete
  5. Can I use this for Wordpress?

    ReplyDelete
  6. Thanks for sharing that :) Just curious though...could you also open a new browser window (with the destination URL defined in another element) when the click is done on the "changeText" element?

    ReplyDelete
  7. hi,
    if i want to load a html content ?
    and if i want to applicate a fade effect ?thx

    ReplyDelete
  8. Thanks for your code. Helped me out a lot. I was trying Ajax through JQuery and wanted to load dropdown box on click of a button.

    Thanks Again..

    Gaurav Kumar
    http://www.OSWebStudio.com

    ReplyDelete
  9. Thanks for sharing such a straight forward example.

    This is my jQuery Hello world moment!

    ReplyDelete
  10. Simple and to the point! Thanks!

    ReplyDelete