Reputation: 8762
I have two span tags. I'd like to swap the content between them once the user clicks on one of them. If the user clicks once more, swap the content again and so on.
$(".sectionTitleText").livequery("click", function () {
var editor = $(this).attr("data-edit-id");
var viewer = $(this).attr("data-view-id");
//Swap code
});
Upvotes: 2
Views: 6805
Reputation: 3875
You can create a temp object :
$element1 = $("#selector1");
$element2 = $("#selector2");
var $temp = $("<div>");
$element2.after($temp);
$element1.after($element2);
$temp.after($element1);
$temp.remove();
It's possible with before() too. It's possible because after() and before() move (or add) object in DOM, not duplicate it.
Upvotes: 0
Reputation: 339816
If both nodes are the only children of the same parent, just do this:
$('#parent').prepend($('#parent').children().last());
This should take whichever element is currently last, and make it first.
See http://jsfiddle.net/alnitak/wt4VZ/ for demo.
If that doesn't apply, try:
var el1 = $('#element1');
var el2 = $('#element2');
var tag1 = $('<span/>').insertBefore(el1); // drop a marker in place
var tag2 = $('<span/>').insertBefore(el2); // drop a marker in place
tag1.replaceWith(el2);
tag2.replaceWith(el1);
The idea here is that the two temporary spans just act as place holders into which the original elements will be dropped, without serialising or otherwise messing with those elements.
See http://jsfiddle.net/alnitak/bzKXn/ for a demo of that.
Upvotes: 4
Reputation: 25582
Here's a generic jQuery function to do it:
$.fn.swapWith = function(swap_with_selector) {
var el1 = this;
var el2 = $(swap_with_selector);
if ( el1.length === 0 || el2.length === 0 )
return;
var el2_content = el2.html();
el2.html(el1.html());
el1.html(el2_content);
};
See this jsFiddle for an example.
Upvotes: 3
Reputation: 8335
I don't know what livequery is, but what about this:
function swapEditView(){
var temp = $('#data-edit-id').html();
$('#data-edit-id').html($('#data-view-id').html());
$('#data-view-id').html(temp);
}
$('#data-edit-id').click(function(){
swapEditView();
});
$('#data-view-id').click(function(){
swapEditView();
});
Upvotes: 0
Reputation: 9432
You need too keep the text in the span :
var firstText = $('#first_span_id').text()
var secondText = $('#second_span_id').text()
and then swap it :
$('#first_span_id').text(secondText)
$('#second_span_id').text(firstText)
If your span contains html tags, you may want to use .html() instead of .text()
Upvotes: 0
Reputation: 10400
This is a simple content swapping.
var temp = $("#span1").html();
$("#span1").html($("#span2").html());
$("#span2").html(temp);
Upvotes: 2
Reputation: 94469
$(".sectionTitleText").livequery("click", function () {
var editor = $("#span1"); //put your ids here
var viewer = $("#span2");
editorContent = editor.clone();
viewerContent = viewer.clone();
editor.replaceWith(viewerContent);
viewer.replaceWith(editorContent);
});
Upvotes: 3