Select <li> from div1, click the button, go to div2
I know this will be easy to do for someone with javascript experience, but I'm drawing a space.
I have a list of items:
<div id="left-side"> <ul> <li><div>Item 1</div></li> <li><div>Item 2</div></li> </ul> </div> <input id="addElement" type="button" value="->"/> <div id="right-side"> </div>
I would like to highlight (change the background color) the selected list item on the left, and then click on the button, move the selected item to the right div and finally change the background color.
I have seen this many, many times on the Internet. But life cannot for me, figure out how to do it.
Something like this (jquery) should do the trick:
// make the items selectable by toogling an 'active' class $('#left-side li').click(function() { $(this).toggleClass('active'); }); // on click of the move button $('#addElement').click(function() { // get the items to move var $items = $('#left-side li.active'); // remove their active state $items.removeClass('active'); // append them to the right side list $('#right-side ul').append($items); });
As you can see, the code is really pretty forward.
I also created a small demo example: http://jsfiddle.net/NbcS9/
change
If you only want to select one item on the left, you can do something like this:
// make the items selectable by toogling an 'active' class $('#left-side li').click(function () { // remove active class from all other items $('#left-side li').not($(this)).removeClass('active'); // toggle the active class on the clicked item $(this).toggleClass('active'); });
And updated fiddle: http://jsfiddle.net/NbcS9/1/
Using pure JavaScript would be difficult for this, but with jQuery you can do it easily. Add click events to two divs that add the selected text of the other to yourself. to get the selected data add this function:
function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; }
Also, I would take a look at jQuery Draggable (). sounds like something that may be related to your desired end result. http://jqueryui.com/draggable/
CSS
.highlighted { background: yellow; }
HTML:
<div id="left-side"> <ul> <li><div>Item 1</div></li> <li><div>Item 2</div></li> </ul> </div> <input id="addElement" type="button" value="->"/> <div id="right-side"> <ul></ul> </div>
JS:
$('#left-side').find('li').on('click', function(event) { $(this) .siblings().removeClass('highlighted') .end() .addClass('highlighted'); }); $('#addElement').on('click', function(event) { event.preventDefault(); $('#left-side').find('li.highlighted').appendTo('#right-side ul')); });