How to use the preventDefault() Method
This is an "event" method. Actually it is quite clever, the thing is I am not sure how you would be aware of it unless you had been on an advanced ECMAScript training course. I came across it when looking at a JSON page search. At first I was a little perplexed but it now makes a little more sense as the example added EventListeners to form elements on the page.
The JavaScript for page search
document.addEventListener('submit', handleSearch);
document.addEventListener('reset', function(event){
event.preventDefault();
render(books);
The preventDefault() is also used before the handlesearch code. This is to prevent the search being made unless the form element was submitted. i.e. not when the page is loaded.
More JavaScript for page search
var handleSearch = function(event) {
event.preventDefault();
What MDN say:
The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.
Propargation of events
The response to an event, such as a mouse click, can be prevented
stopPropagation()
The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method.
stopImmediatePropagation()
The stopImmediatePropagation() method of the Event interface prevents other listeners of the same event from being called.
If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. If stopImmediatePropagation() is invoked during one such call, no remaining listeners will be called.
The following code can benefit from formating:
The full JavaScript for page search
var render = function(data) {
var app = document.getElementById('app');
var booksHTMLString = '<ul>'+
data.map(function(book){
return '<li>'+
'<strong>Title: </strong>' + book.title + '<br/>' +
'<strong>Subtitle: </strong>' + book.subtitle + '<br/>' +
'Author: ' + book.author + '<br/>' +
'Category: ' + book.category + '<br/>' +
'Publisher: ' + book.publisher + '<br/>' +
'</li>';
}).join('');
+ '</ul>';
app.innerHTML = booksHTMLString;
}
render(books);
var handleSearch = function(event) {
event.preventDefault();
// Get the search terms from the input field
var searchTerm = event.target.elements['search'].value;
// Tokenize the search terms and remove empty spaces
var tokens = searchTerm
.toLowerCase()
.split(' ')
.filter(function(token){
return token.trim() !== '';
});
if(tokens.length) {
// Create a regular expression of all the search terms
var searchTermRegex = new RegExp(tokens.join('|'), 'gim');
var filteredList = books.filter(function(book){
// Create a string of all object values
var bookString = '';
for(var key in book) {
if(book.hasOwnProperty(key) && book[key] !== '') {
bookString += book[key].toString().toLowerCase().trim() + ' ';
}
}
// Return book objects where a match with the search regex if found
return bookString.match(searchTermRegex);
});
// Render the search results
render(filteredList);
}
};
document.addEventListener('submit', handleSearch);
document.addEventListener('reset', function(event){
event.preventDefault();
render(books);
})
The code above can be found on my page page_search.html.