Morpheus
Morpheus

Reputation: 997

Search icon on click popup search box

I'm having troubles with icon and popup when icon is pressed. Here's part of the code:

<div class="searchlink" id="searchlink">
   <i class="fa fa-search fa-custom"></i>
   .... 
</div>
$(function() {
    var $searchlink = $('#searchlink');

    $searchlink.on('click', function(e) {
        var target = e ? e.target : window.event.srcElement;
        if ($(target).attr('id') == 'searchlink') {
            if ($(this).hasClass('open')) {
                $(this).removeClass('open');
            } else {
                $(this).addClass('open');
            }
        }
    });
});

Full code: jsfiddle

It is not showing when I press the icon, it shows if I press around icon. What should I change? Thanks.

Upvotes: 2

Views: 10946

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337637

Your JS code has a couple of logic issues. Your primary issue is the use of e.target to get the element which raised the event. This is a problem as you have a lot of child elements within the event bound element. To solve it you can simply use the this keyword to refer to the element that raised the event.

Then you can remove the if statement checking the id of the element. This is redundant as the click event is bound to that id, so it will always be true.

Finally you can simplify the class checking logic by just using jQuery's toggleClass() method. Try this:

$(function() {
    $('#searchlink').on('click', function(e) {
        $(this).toggleClass('open');
    });
});

Working example

Upvotes: 2

Related Questions