19 March, 2022

jQuery Upgrade

First replace old jQuery with latest version and add the jQuery migrate plugin:

<head>
  <script src="./jquery-3.6.0.js"></script>
  <script src="./jquery-migrate-3.3.2.js"></script>
</head>

Then open the console to see messages from the migrate plugin. Here are som examples of what to replace with new code:

load

$(window).load(function() { })

// replace with
$(window).on('load', function() { })

change

$('#x').change(function() { })

// replace with
$('#x').on('change', function() { })

keydown

$('#x').keydown(function() { })

// replace with
$('#x').on('keydown', function() { })

keypress

$('#x').keypress(function() { })

// replace with
$('#x').on('keypress', function() { })

change

$('#x').change()

// replace with
$('#x').trigger('change')

focus

$('#x').focus()

// replace with
$('#x').trigger('focus')

removeAttr

$('#x').removeAttr('disabled')

// replace with
$('#x').attr('disabled', false)

isFunction

if ($.isFunction(x)) { }

// replace with
if (typeof x === 'function') { }

isArray

if ($.isArray(x)) { }

// replace with
if (Array.isArray(x)) { }

trim

$.trim(x)

// use String.trim()
x.trim()

success

$.ajax({}).success(function(data) { })

// replace with
$.ajax({}).done(function(data) { })

error

$.ajax({}).error(function(data) { })

// replace with
$.ajax({}).fail(function(data) { })

Testing

Here is a simple html file to test some jQuery calls:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  
  <script src="./jquery-3.6.0.js"></script>
  <script src="./jquery-migrate-3.3.2.js"></script>
  <script>
    $(window).on('load', _ => console.log('window on load'))
  </script>
</head>
<body>
  <input id="x" maxlength="50" type="text" title="" placeholder="" value="">
  <input id="y" type="button" value="Search" disabled />
  <script>
    function x() {
      console.log('function x called')
    }

    $('#x').on('change', _ => console.log('on change'))
    $('#x').on('keydown', _ => console.log('on keydown'))
    $("#y").on('click', _ => $('#x').change()/*$('#x').trigger('change') console.log('button clicked')*/)
    $('#x').attr('disabled', true)
    $('#y').attr('disabled', false)
    if (typeof x === 'function') {
      console.log('x is a function')
      x()
    }
</script>
</body>
</html>