JavaScript – How To Execute a Function with Variables when Button is Clicked

If we take the following code, we call the Log function without the (). This calls the Log function every time the buttonObject is clicked.

// Find object id myButton
let buttonObject = document.getElementById('myButton')  

// Add an event listener, and run Log function when clicked.
buttonObject.addEventListener('click', Log) 
// If we call Log(), it will immediately trigger the function

function Log () {
  console.log("Hello World!")
}

But what if we want to pass in a variable to the Log function? We can’t run Log('some text') as the function will run before we click the object.

We can however wrap the Log function inside of an anonymous function like so

let buttonObject = document.getElementById('myButton')

// Now Log() function will be run with the variable getting passed.
buttonObject.addEventListener('click', () => {
  Log('Hello World!')
})

function Log (textVariable) {
  console.log(textVariable)
}

Our Log function gets triggered when the object is clicked, and the variable is passed properly. You can swap out thy arrow function with a nameless function ()

JavaScript Functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

What is a function? A function is a block of code that does a particular task.

JavaScript has 3 different types of functions

  1. Function Declaration
  2. Function Expression
  3. Arrow Function Expression

Functions can also be named, or anonymous. There are a couple helpful things anonymous functions can help with.

Function Declaration

Function declaration’s are your standard functions. Syntax is as follows

function add(num1, num2) {
  return num1 + num2
}


console.log(add(1, 2));

Function Expression

A function expression can be thought of as a variable that is a function. We define function expressions like so

const add = function myFunction (num1, num2) {
  return num1 + num2;
}

console.log(add(1, 2));

Function expressions can be anonymous. To make the above function anonymous, remove “myFunction”. It would then read “function (num1, num2)”

Typically it is a good idea to name your function expressions as debugging anonymous functions can be a bit more difficult.

A warning about function expressions. They are not hoisted like function declarations. Just be sure that you define the function expression before you call it.

Arrow Function Expressions

Arrow functions are a compact version of function expressions that are always anonymous. They can be a bit tricky to get the syntax correct. Refer to the link below to get a better list of syntax and use. Arrow functions also have some other limitations. They do not have bindings to this, arguments or super.

const add = (num1, num2) => num1 + num2;

console.log(add(1, 2);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Anonymous Functions

Anonymous functions are functions that don’t have a name. For instance

function () {
  do something
}

Does not have a name and is therefore an anonymous function. Arrow functions are always anonymous.

When would you need to use an anonymous function?

One good example is when you want to call a named function from a timer, or when a button is clicked. For instance

// Find object id myButton
let buttonObject = document.getElementById('myButton')  

// Add an event listener, and run Log function when clicked.
buttonObject.addEventListener('click', Log) 
// If we call Log(), it will immediately trigger the function

function Log () {
  console.log("Hello World!")
}

But what if we want to pass in a variable to the Log function? We can’t run Log('some text') as the function will run before we click the object.

We can however wrap the Log function inside of an anonymous function like so

let buttonObject = document.getElementById('myButton')

// Now Log() function will be run with the variable getting passed.
buttonObject.addEventListener('click', function () {
  Log('Hello World!')
})

function Log (textVariable) {
  console.log(textVariable)
}

And our Log function gets triggered when the object is clicked, and the variable is passed properly. You can swap out function () with an arrow function () =>

JavaScript Delete Object if it Collides or Overlaps with another object that has CSS Class X

Imagine we have a page that has anywhere from 1 to 100 floating blocks. Now what if I want the block(s) to disappear if it runs into another type of block or a boarder? How would we do that?

First lets get a list of all elements with X and Y class. We could swap one of these classes out for an ID if we wanted to.

const elements1 = document.querySelectorAll('.boxes')
const elements2 = document.querySelectorAll('.borders')

The variable elements1 and 2 are both arrays of all the elements that have class .boxes and boarders.

Now lets create a function to detect a collision.

function detectCollision(class1, class2) {
  for (let i = 0; i < class1.length; i++) {
    const e1Rectangle = class1[i].getBoundingClientRect()
    for (let i2 = 0; i2 < e2.length; i2++) {
      const e2Rectangle = class2[i2].getBoundingClientRect()
      if (
        e1Rectangle.left < e2Rectangle.right &&
        e1Rectangle.right > e2Rectangle.left &&
        e1Rectangle.top < e2Rectangle.bottom &&
        e1Rectangle.bottom > e2Rectangle.top
      ) {
        destroyElement(class1[i])
        destroyElement(class1[i2])
      }
    }
  }
}

This function takes two arrays as inputs, loops over each array object and compares to see if any are overlapping. If they are overlapping, run the destroyElement() function for those two specific elements.

Create the destroyElement function with

 function destroyElement(element) {
  elementId.parentNode.removeChild(elementId)
}

Here is our full code

const elements1 = document.querySelectorAll('.boxes')
const elements2 = document.querySelectorAll('.borders')

function detectCollision (class1, class2) {
  for (let i = 0; i < class1.length; i++) {
    const e1Rectangle = class1[i].getBoundingClientRect()
    for (let i2 = 0; i2 < e2.length; i2++) {
      const e2Rectangle = class2[i2].getBoundingClientRect()
      if (
        e1Rectangle.left < e2Rectangle.right &&
        e1Rectangle.right > e2Rectangle.left &&
        e1Rectangle.top < e2Rectangle.bottom &&
        e1Rectangle.bottom > e2Rectangle.top
      ) {
        destroyElement(class1[i])
        destroyElement(class1[i2])
      }
    }
  }
}

// Element is element[arraynumber].etc
function destroyElement(element) {
  elementId.parentNode.removeChild(elementId)
}

// Every second, let's run our collision function to check for collisions
setInterval(function () {
   detectCollision(elements1, elements2)
  }, 1000)