Sam Opoku
Sam Opoku

Reputation: 69

Changing An Elements Content

I would like to change the content of a element with a button click and then have it return back to its original message. How Would i do this preferable with toggle class if possible.

<doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Day Practice</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"> </script>

</head>
<body>
<h1> HotDogs</h1>
<input type=button id=button value=button>
<script>
$("#button").click(function(){ 
$("h1").html("Change to this");
});


</script>

This changes the header with a button, but I don't know how to revert it when I click on the button again. Maybe Toggle Class, I don't know.

Upvotes: 2

Views: 48

Answers (4)

icecub
icecub

Reputation: 8773

Since you prefered to do this with toggleClass(), here you go:

$(document).ready(function(){

    var oldContent;

    $("#button").click(function(){
        if($(".newCont")[0]){
            $("h1").html(oldContent);
        } else {
            oldContent = $("h1").html();
            $("h1").html("New text here");
        }

        $("h1").toggleClass("newCont");
    });
});

Upvotes: 0

mbinette
mbinette

Reputation: 5094

You can try this:

var alternate_text = "Change to this";
$("#button").click(function(){ 
    var temp = $("h1").html()
    $("h1").html(alternate_text);
    alternate_text = temp; // Switch the two instances of text.
});

Upvotes: 0

GrafiCode
GrafiCode

Reputation: 3374

this should solve:

$( "#button" ).toggle(function() {
  $("h1").html("Change here");
}, function() {
  $("h1").html("Revert back here");
});

Upvotes: 1

enigma
enigma

Reputation: 3491

Set a flag to toggle and check, and store the old text whenever you change it. An example:

var flag = false;
var old_text = "";

$("#button").click(function () {
    if (flag) {
        $("h1").html(old_text);
    } else {
        old_text = $("h1").html();
        $("h1").html("Change to this");
    }
    flag = !flag;    
});

Upvotes: 0

Related Questions