Upgrade to Pro — share decks privately, control downloads, hide ads and more …

jQuery Bad Practices

Filipe Costa
November 09, 2013

jQuery Bad Practices

Let's learn some bad jQuery practices to avoid them.

Filipe Costa

November 09, 2013
Tweet

More Decks by Filipe Costa

Other Decks in Programming

Transcript

  1. ;(function(window, document, $) {! var isInputSupported = 'placeholder' in document.createElement('input');!

    var isTextareaSupported = 'placeholder' in document.createElement('textarea');! var prototype = $.fn;! var valHooks = $.valHooks;! var propHooks = $.propHooks;! var hooks;! var placeholder;! ! if (isInputSupported && isTextareaSupported) {! placeholder = prototype.placeholder = function() {! return this;! };! placeholder.input = placeholder.textarea = true;! } else {! ! placeholder = prototype.placeholder = function() {! var $this = this;! $this.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')! .not('.placeholder')! .bind({! 'focus.placeholder': clearPlaceholder,! 'blur.placeholder': setPlaceholder! }).data('placeholder-enabled', true).trigger('blur.placeholder');! return $this;! };! placeholder.input = isInputSupported;! placeholder.textarea = isTextareaSupported;! hooks = {! 'get': function(element) {! var $element = $(element);! var $passwordInput = $element.data('placeholder-password');! if ($passwordInput) {! return $passwordInput[0].value;! }! return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;! },! 'set': function(element, value) {! var $element = $(element);! var $passwordInput = $element.data('placeholder-password');! if ($passwordInput) {! return $passwordInput[0].value = value;! }! if (!$element.data('placeholder-enabled')) {! return element.value = value;! }!
  2. Yo

  3. DRY

  4. function getCities(state) {! $.ajax({! url: '/cities',! type: 'get',! data: state,!

    success: function(data) {! $('.user-form-states-select').html(data);! }! });! }
  5. //functions.js! function getCities(state) {! return $.ajax({! url: '/cities',! type: 'get',!

    data: state! });! }! ! //user.js! var FillSelectBox = function(data) {! $('.user-form-state-select').html(data);! }! ! getCities('CE').then(FillSelectBox);
  6. var names = ["Greg", "Peter", "Kyle", "Danny", "Mark"];! $.each(names, function(index,

    value) {! $("ul.people").append("<li id=" + index + ">" + value + "</li>");! });
  7. var names = ["Greg", "Peter", "Kyle", "Danny", "Mark"],! list =

    $("ul.people");! $.each(names, function(index, value) {! list.append("<li id=" + index + ">" + value + "</li>");! });
  8. var names = ["Greg", "Peter", "Kyle", "Danny", "Mark"],! ! list

    = $("ul.people"),! ! listItems = "";! ! $.each(names, function(index, value) {! listItems += "<li id=" + index + ">" + value + "</li>";! });! ! list.append(dynamicItems);
  9. jk