SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Addict
    Join Date
    Sep 2006
    Posts
    238
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    jQuery - replace content on click

    Hello

    I would like to know how I can do this on jQuery.
    How can I replace content with something else when I click on the content or when I click on a link.

  2. #2
    SitePoint Enthusiast
    Join Date
    Jun 2011
    Location
    Dartmouth, MA, USA
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In the head section of your HTML, you bind an event handler to the click action of an element, and then take the appropriate action within the event handler.

    Let's say that the thing you click has an id of "button", the element you want to change the content of has an id of "content", and the new content you wish to put into it is "new content". Then you would do something like this:

    Code JavaScript:
    $(document).ready(function() {
      $("#button").click(function() {
        $("#content").text("new content"); // Use .html() if the content has HTML in it
      });
    });

    This simply replaces the content of an element when something else is clicked, which I'm not sure is entirely what you want since I'd imagine you're after something a little more complicated (maybe retrieving the data from a server or something?), but it's a start. If the element to be clicked and the element to have its content replaced are one and the same, then just take the code above and change "#content" to "this" (without the quotes).

  3. #3
    SitePoint Enthusiast
    Join Date
    Jun 2011
    Location
    Dartmouth, MA, USA
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Also, if it's a link that you're clicking on, the function you pass to .click() should look like this:

    Code JavaScript:
    function(e) {
    // ... code to replace the content ...
    e.preventDefault(); // Prevents the browser from trying to follow the link
    }

  4. #4
    SitePoint Addict
    Join Date
    Sep 2006
    Posts
    238
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi, thank you for your response.

    I understand that it replaces the content within the div. Is it possible to replace the div with another div?

  5. #5
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,196
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    jQuery has a built in method to do this called .replaceWith()


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •