$elem.on('keydown', function(e) {
if (e.keyCode == 27) {
//...
}
});
What is the magic number 27? People who often face the code immediately say - this is the key ESC. But most developers, especially beginners, do not remember the code, have to get into the search engine and waste their time.
var id = $(this).attr('id').substring(8);
As in the previous example, the developer has to wonder - what is that number 8. He has to climb in the html code, etc.
var last_id = $('#answer_pid' + id + ' li:first div').attr('id').substr(7);
As the result the slightest change in layout will lead to change js code.
<div class="comment" id="comment_123"></div>
var id = $(this).attr('id').substring("comment_".length);
Even better (or at least no hardcoded numbers), but still, this approach too strongly attached js code to html.
<div class="comment" data-id="123"></div>
then get the ID will be very simple:
var id = $(this).attr('data-id');
or
var id = $(this).data('id');
About the differences in the data and attr methods there is a set of articles.
$('.comment a.delete').click(function(){
//
});
And we have a problem: how to add the same handler to the new item (such as a dynamically loaded comment). And here I saw a lot of decisions, including the redefinition of all the handlers again (often by copy-paste content of the handlers):
$('.comment a.delete').unbind('click').click(function() {
//
});
Solution: jQuery 1.7 has a method
on, which binds handlers, filtering elements by selector. Example:
$('body').on('click', 'a.external', function(e) {
// Function will be called when you click on any link with a class [b]external[/b]
});
It is important that the handler works for dynamically created objects.
$('body').on('mousemove', selector, function() {
//
});
$('a').on('click', function() {
// handler 1
});
$('a').on('click', function() {
// handler 2
});
Now, suppose that we need to remove the second handler of reference. But then the bad luck - $('a').off('click') will remove both the handlers. To the aid come namespaced events. Let's rewrite the code above:
$('a').on('click.namespace1', function() {
// handle 1
});
$('a').on('click.namespace2', function() {
// handle 2
});
Now it is possible to remove the second handler by calling $('a').off('click.namespac
$(".info").html("")
because in the past they've used the convenient phrase .innerHTML = "". And above the preferred option:
$(".info").empty()
These programmers often clean item before placing a new information in it:
$(".info").html("").html("<b>Ok</b>")
But do not forget - you write on jQuery! And he cares about you, and .html() will clear itself before inserting a new element value.
$(".info").remove()
Furthermore...
$("#history").css("display", "none")
$("#description").css("display", "none")
$("#category").css("display", "none")
$("#contact").css("display", "none")
you say "Hide history, hide the description, hide categories, hide contacts." Most likely, you said: "Hide history, description, category, and contacts." So write it:
$("#history, #description, #category, #contact").hide()
and do not forget that jQuery loves you, and there are methods to hide - .hide(), and to show - .show() - elements.
$(selector).hover(function() {
tooltip.show()
}, function() {
tolltip.hide()
})
Note, that starting with version 1.8 .hover() function is deprecated.
var person = $(".name").parent().parent().parent()
It is clear that here is an attempt to get to the needed parent, which has important information, or has another item you want. And what if while you were on vacation, your $ (". Name") nestles in a different place, but under all the same person? Many craftsmen cyclically cause .parent() to the desired item. More experienced know that there is .parentsUntil(selector), which will return all parents to a specified (excluding itself). But still cumbersome decision:
var person = $(".name").parentsUntil(".person").last().parent()
But there's an obvious way:
var person = $(".name").closest(".person")
If we remember that we write code the way we put it into words, then this option is more suitable because of its transparency and brevity.
$.post(url, data, function(data) {
data = $.parseJSON(data);
// ...
});
2. Added try-catch block:
$.post(url, data, function(data) {
try {
data = $.parseJSON(data);
} catch (e) {
return;
}
// ...
});
3. Learn from the documentation that to the $.post() method could be passed dataType as last parameter (which lost in the abyss of the code, if success function does not fit the screen):
$.post(url, data, function(data) {
// ...
}, 'json');
Very few web developers add handlers for the error situations. This is mainly due to laziness or unwillingness to spend the extra 5 minutes of time, or the developers just believe that mistakes will never happen. If the developer decided to add an error handler, you get something like:
$.post(url, data, function(data) {
// ...
}, 'json').error(function() {
// ...
});
In my opinion - it's awful unreadable. Also writing each time the error handler - it tiresome. Therefore, you can set the default error handler for all ajax requests, such as:
$.ajaxSetup({
error: function() {
// ...
}
});
You can define any other repeated ajax parameters:
$.ajaxSetup({
dataType: "json",
data: {
user_id: userId
},
error: function() {
// ...
}
});
Now we do not have to specify every time these parameters in queries:
$.ajax({
data: {
product_id: productId
},
success: function(json) {
console.log(json)
},
alert: "Loading..." // For what? See below...
})
<div id="popup" class="centered-bold-red"></div>
And link it to our requests:
$("#popup").ajaxSend(function(event, xhr, options) {
$(this).text(options.alert || "Please wait...").show()
}).ajaxStop(function() {
$(this).fadeOut("fast")
})
.ajaxSend() calls the handler every time there is an AJAX-request. Here we derive the transmitted (see above) a message or default one.
$.ajax({
data: {
action: "search-name",
name: $("#name").val()
},
beforeSend: function() {
$(searchForm).trigger("start.search")
},
complete: function() {
$(searchForm).trigger("finish.search")
}
})
Now we can just tell (e.g. in the comments) that anyone can subscribe to the events start.search and finish.search:
$(searchForm)
.on("start.search", function() {
// Show preloader
})
.on("finish.search", function() {
// Hide preloader
})
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (5)
Commented:
Can you re-read your first paragraph or get a native English speaker to look at it? It is very hard to read.
Otherwise a good idea for an article
Author
Commented:Commented:
Commented:
-Matt
Author
Commented: