简体   繁体   中英

Move selected objects from one place to another and back again to original position javascript

I am making a keyword selector in where a user selects one or more keywords from one box. Those keywords that are selected are then taken out of the original box and put into the one alongside it, displaying the selected keyword.

I wish to store the keyword elements in an array but i am having trouble figuring out how the user would actually click on the element and display it in the opposite box. The only way I seem to be making any progress is with onclick() functions etc... for the individual elements but thats not what I am looking for.

Is it possible to move these elements from within their contained div to the the empty box div ??. Any advise or responses on this would be appreciated, attached is a code snippet to get a better grasp on the problem. Thanks everyone.

 var kwords = [ "audi", "bmw", "chevrolet", "honda", "mercedes", ] function car1() { document.getElementById("inner").style.color = 'blue'; } 
 #boxleft { border: 5px solid blue; background-color: gray; height: 250px; width: 250px; margin-bottom: 20px; float: left; } #boxright { border: 5px solid blue; background-color: gray; height: 250px; width: 250px; margin-bottom: 20px; float: left; display: inline; } #inner { color: red; } 
 <div id="boxleft"> <div id="inner" onclick="car1();">audi</div> <div id="inner1">bmw</div> <div id="inner2">chevrolet</div> <div id="inner3">honda</div> <div id="inner4">mercedes</div> </div> <div id="boxright"></div> 

You can attach click listener to many elements at once. Take a look at this codepen .

What is happening here:

  1. document.querySelectorAll('.keyword') looks for all elements with keyword class in the document (take a look how I've changed the HTML section)
  2. Inside forEach loop, line element.addEventListener('click', toggleKeyword) adds click listener to every found element (which is equivalent to manually assigning onClick attribute)
  3. Now when you click on a keyword, toggleKeyword function is executed:
  4. var element = event.target; is the element you clicked
  5. boxLeft and boxRight variables are these two divs with boxLeft and boxRight ids
  6. var newParent = element.parentNode.id === 'boxleft' ? boxRight : boxLeft; this line checks which the new parent element should be, if you clicked on div inside the leftbox it should go to the rightbox and vice versa.
  7. Finally we remove element from it's current parent and add to the opposite one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM