Tim Goddard Tim Goddard - 6 months ago 7
Javascript Question

Jquery - swapping two DIV's html content

I'm having trouble getting this method of swapping to work, using an 'each' loop after a button is pressed.

The loop iterates, but text does not do as thought.

perhaps i'm using the wrong method of assigning html to these tagged divs?.



$(function() {
$('.direction-toggle').click(function() {
$(this).toggleClass('off');
$("#CW").each(function(i, el) {
if ($(el).html() == "↺") {
$(el).html("↻");
} else if ($(el).html() == "↻") {
$(el).html("↺");
}
});
});
});

.direction-toggle {
margin: auto;
width: 30px;
background: white;
cursor: pointer;
border: 2px solid black;
border-right-width: 15px;
padding: 0 5px;
border-radius: 5px;
text-decoration: none;
transition: all .5s ease;
}
.direction-toggle.off {
background: rgba(200, 230, 255, 1);
border-right-width: 2px;
border-left-width: 15px;
}
#CW,
#CCW {
float: right;
}

<div class="twist-left">&#65513; R 1
<div id="CCW" class="direct">&#8634;</div>
<div class="">
</div>
</div>
<div class="twist-right">L 1
<div id="CW" class="direct">&#8635;</div>&#65515;
<div class="">
</div>
</div>

<div class="direction-toggle">
&nbsp;
</div>





http://jsfiddle.net/wJftm/1/

Answer

If i understand you properly, use this code:

$(function() {
  $('.direction-toggle').click(function() {
    $(this).toggleClass('off');
    var twistLeftHtml  = $('.twist-left').html();
    var twistRightHtml = $('.twist-right').html();
    $('.twist-left').html(twistRightHtml);
    $('.twist-right').html(twistLeftHtml);
  });
});

Or this:

$('.direction-toggle').click(function() {
    $(this).toggleClass('off');
    var twistLeftDirectHtml  = $('.twist-left .direct').html();
    var twistRightDirectHtml = $('.twist-right .direct').html();
    $('.twist-left .direct').html(twistRightDirectHtml);
    $('.twist-right .direct').html(twistLeftDirectHtml);
});

And remember that id attribute must be unique in DOM. Selection by id $('#CW') will return only first matched element.

JSFiddle

Comments