Ipomea
Ipomea

Reputation: 151

Onclick event on search results with javascript

I have a list of search results and want to be able to click each one of those to display their content else where. So far my code looks like this.

<% @found.each do |f|  %>
     <div class="col-sm-3 motion-box" >
        <div class="motion-content" id="preview">
            <h4>role: <%= f.role %></h4>
                <p>mood: <%= f.mood %><br/>
                    description:
                    <% f.param.each do |a| %>
                        <%= a %>
                    <% end %></p>
            <div>
                <button class="btn btn-default btn-sm">BVH</button>
                <button class="btn btn-default btn-sm">C3D</button>
                <button class="btn btn-default btn-sm">FBX</button>
            </div>
        </div>
     </div>
<% end %>

I tried the followning two javascript functions but both only works on the first listelement.

<script type="text/javascript"> 
        $( ".motion-content" ).each(function() 
        {
            alert("Achtung");
        });
</script>

and

document.getElementById("preview").onclick = function () {
    alert("Achtung!");
}

But the first one just opens an alter for every result and I cant get it to do it just onclick and the second one only works on the first search result.

What can I do?

Upvotes: 1

Views: 1577

Answers (1)

godtail
godtail

Reputation: 189

//this will add click listener on each conform '.montion-content' CSS selectors element
$('.motion-content').on('click', function() {
    alert('clicked');
});

/*this will add click listener on [parentDom] 
 and if this element conform to the 
 CSS selectors '.montion-content' will call the function*/
$('[parentDom]').on('click', '.motion-content', function() {
   alert('clicked');
});

see document here

Upvotes: 2

Related Questions