Cannot Change a Variable Using a Method External to document ready Function

I declared a variable called handleExists in document ready function and initialized it to false. When I click on a DIV whose ID is ‘block’ I would like to change the value of this variable to true if its value is false but it is not working.

Please see my code

Hi there!

It’s because you’re passing only value to createDragHandle, to change value you have few options:

  1. Make it shared variable - for example create IIFE: (function() { var handleExists = false; $(this).click(...) function createDragHandle(...) })()
  2. Pass function that changes variable in it’s .ready(function(){ … }) scope like that https://jsfiddle.net/4r7egubx/
  3. (I would not recommend) make handleExists a global scope variable - window._MY_APP_SETTINGS = { handleExists: false } and access that. Again, would highly advice against this one in favor of IIFE way
1 Like

Hi @liagapi555, here are 2 more options:

  1. Wrap handleExists in an object, which will indeed get passed by reference:

    $(document).ready(function () {
      var state = { handleExists: false }
    
      $('#block').click(function (e) {
        createDragHandle(state)
      })
    })
    
    function createDragHandle (state) {
      if (state.handleExists) {
        alert('Handle exists!!')
      } else {
        alert('Handle not yet exists!!')
        state.handleExists = true
      }
    }
    
  2. Don’t modify handleExists from inside createDragHandle() at all, but just return the new value:

    $(document).ready(function () {
      var handleExists = false
    
      $('#block').click(function (e) {
        handleExists = createDragHandle(handleExists)
      })
    })
    
    function createDragHandle (exists) {
      if (exists) {
        alert('Handle exists!!')
      } else {
        alert('Handle not yet exists!!')
        // Return false here if creating the
        // drag handle fails for some reason
      }
    
      return true
    }
    

    Personally I’d prefer this latter approach as it keeps createDragHandle() pure, making your code easier to test and reason about.

Thank you all for your input. I will to use them in my work.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.