event.preventDefault not working

event.preventDefault not working
0.0 0

#1

I’m running into a problem with event.preventDefault not working. In line 92 of this pen it’s not working, but I made this pen to test, and it works.

The background is that I’m going to generate a list of search results, and want the user to be able to click them to add them into the master list. The divs in the master list include links to their respective Twitch channels. I thought the easiest way to do it would be to include the <a> in the search result, but slap a preventDefault into the function that moves it from the search result list to the master list, and proceed with code to make the move. (For testing purposes, so I don’t have to keep running searches to launch the search result modal, I changed the selector to .s8, which includes the status divs already appearing on the page. The test pen, set up with the same Materialize and jquery CSS and JS, is successfully repressing links on .inner, even when it’s part of a chip. So what is different between the two pens? Is it the fact that the code in the first instance has been “inserted” by a jquery operation, rather than “hardcoded” from the start?


#2

Kind of. The difference is actually that event handlers are bound early in the page loading process. When you generate new elements, they weren’t around for event binding and so don’t know anything about the functions you’ve defined. There are two options:

  1. Assign event handlers after you generate the element
$("#searchResults").append("<div id='" + data.channels[i].display_name + "', class='chip row hoverable result'><a href='" + data.channels[i].url + "' target='_blank'><div class='col s1 logo'><img src='" + logo + "'></div><div class='col s2 truncate'>" + data.channels[i].display_name + "</div><div class='col s8 truncate'>" + game + "</div></a><div class='col s1'> <i class='close material-icons'>close</i></div></div>").click(clickEventHandlerFunction); //define the function elsewhere
  1. The preferred method would be to use event delegation. This is done in jQuery when you define the event handler. Choose an element that will be common to your generated elements and exists at startup, then pass the element you want to actually bind to in the on() function.
$("#searchResults").on('click', '.s8', function() {/* do stuff */}

This will target all elements with a class of s8 when you click on the element with an id of searchResults, and so doesn’t need to be bound directly to elements with a class of s8.


#3

Thanks! That all makes sense. Except… it still doesn’t seem to be working. I tried both routes, and the links still open. :scream: !!!


#4

Oooooh there it is–forgot the (). Thanks!