I want to use jQuery to dynamically change an html element every time it's clicked, back and forth (from A to B to A to B etc...)
Right now I use an empty <div>
that is filled with jQuery:
$('#cf_onclick').append('<h2>A</h2>');
And then changed:
$(document).ready(function() {
$("#cf_onclick").click(function() {
$("#cf_onclick").html("<h2>B</h2>");
});
});
But I cannot figure out how to move it back to <h2>A</h2>
. I am guessing that .empty()
jQuery function might work...
One way is to use the .toggle()
method, and trigger it for the first time as well
$(document).ready( function(){
$("#cf_onclick").toggle(
function(){$(this).html("<h2>A</h2>");},
function(){$(this).html("<h2>B</h2>");}
).click();
});
demo http://jsfiddle.net/gaby/ufXxb/
Alternatively you could create two h2
tags and just alternate between them.
$(document).ready( function(){
$('#cf_onclick').append('<h2>A</h2><h2 style="display:none">B</h2>');
$("#cf_onclick").click(function(){
$('h2', this).toggle();
});
});
demo http://jsfiddle.net/gaby/ufXxb/1/
Try using the toggle() function: http://api.jquery.com/toggle/ It's a way of alternating an action with each click.
You could do this:
$(document).ready(function() {
$("#cf_onclick").click(function() {
var currentOpt = $("#cf_onclick h2").html();
currentOpt = (currentOpt == 'B' ? 'A' : 'B');
$("#cf_onclick").html("<h2>"+currentOpt+"</h2>");
});
});
Hope this helps