muhaimin
muhaimin

Reputation: 119

addEventListener is not working when on click

Hi i am trying to use addEventlistener on an event firing.But it is not working. When i click on header_search button it works fine and log on console "clicked" and a window opens . On the opened window there is a close button which id is "search-close" . and when i press on the button that does not work.Even it does not console log "clicked". Could anyone help? Is that a browser problem?

var search = document.getElementById('header_search');
var close = document.getElementById('search-close');

console.log(search);
console.log(close);

search.addEventListener('click', function(event){
    console.log("clicked");
    event.preventDefault();
    showFullScreen();
    document.getElementById('search-top').focus();
});

close.addEventListener('click', function(event){
    event.preventDefault();
    console.log("clicked");
    searchClose();
});

function showFullScreen(){
    $('html').prepend('<div class="full-screen-search" />');
    var search_form = document.getElementById('search-header-form').innerHTML;
    $(".full-screen-search").html(search_form);
    $(".full-screen-search").fadeIn(1000);
};

function searchClose(){
    $(".full-screen-search").fadeOut(200);
    $(".full-screen-search").remove();

};

Upvotes: 2

Views: 2966

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

If you are using jQuery, don't use addEventListener and getElementById. That kind of defeats the "more with less" benefits of jQuery. Use .click(function(){...}) or .on('click', function(){...}) and $('#idname')

You are adding your window dynamically, so the close button is not the one you originally found with getElementById('search-close').

Use a jQuery delegated event handler attached to a non-changing ancestor element

e.g.

 $(document).on('click', '#search-close', function(){...

You cannot have duplicate IDs on a page, or only the first can be found. Suggest you change to using classes instead:

 $(document).on('click', '.search-close', function(){...

Delegated events work by listening for events (e.g. click) to bubble up to a non-changing ancestor element. document is the best default of nothing else is closer. It then applies the jQuery selector at event time, so the target does not need to exist when the code was registered.

If you can also provide your page HTML, I will provide a full example of how to better write your code with jQuery :)

Upvotes: 5

Related Questions