Julie Bang Julie Bang - 1 month ago 10
jQuery Question

Move a DOM element Using jQuery

For a school assignment we were asked to make a code using jQuery, so that when you hover over an element in a table it takes the data and put it into three different span elements. I think I am close but it is not working properly and right now it just creates a mess on the page.

<table id="games">
<thead>
<tr><th>Titel</th><th>Genre</th><th>Årstal</th></tr>
</thead>
<tbody id="games_tbody">
<tr class="horror"><td>Outlast</td><td>Horror</td><td>2013</td></tr>
<tr class="rpg"><td>Dragon Age: Inquisition</td><td>Role-playing Game</td><td>2014</td></tr>
<tr class="rpg"><td>Skyrim</td><td>Role-playing Game</td><td>2011</td></tr>
<tr class="horror"><td>Amnesia: The Dark Descent</td><td>Horror</td><td>2010</td></tr>
<tr class="simulator"><td>Scania Truck Driving Simulator</td><td>Simulator</td><td>2012</td></tr>
<tr class="horror"><td>Five Nights at Freddy’s</td><td>Horror</td><td>2014</td></tr>
<tr class="simulator"><td>Sims 4</td><td>Simulator</td><td>2014</td></tr>
<tr class="rts" id="last"><td>Warcraft III: Reign of Chaos</td><td>Real-time Strategy</td><td>2002</td></tr>
</tbody>
</table>

<a href="" id="delete_game" type="button" class="btn">Delete Game</a>

<div class="game-of-the-moment">
<h2>Game of the <em>Moment</em></h2>
<p>
<span id="moment_title"></span>
<span id="moment_genre"></span>
<span id="moment_year"></span>
</p>
</div>


The jQuery I have so far

$("#games_tbody tr").on("mouseover", function(){
$ (this).appendTo("#moment_title");
$ (this).appendTo("#moment_genre");
$ (this).appendTo("#moment_year");
});

Answer

Try this :)

$("#games_tbody tr").on("mouseenter", function(){ //mouseenter is a simpler thing to use
    $("#moment_title").text($(this).children().eq(0).text());
    $("#moment_genre").text($(this).children().eq(1).text());
    $("#moment_year").text($(this).children().eq(2).text());
});

Here I select the different spans, then use this to find the tds within the tr you are hovering over.

using mouseenter makes it so the code doesn't fire when you move the mouse whilst its already inside the tr, and only upon entering the tr instead. Use mouseleave to handle the mouse leaving the element