0
\$\begingroup\$

This is quite a simple function, but I just wanted some opinions on it, like is this the correct way to run a function and check if an element exists or not?

const button = document.querySelector('.js-brand-video--thumbnail')
const iframe = document.querySelector('.js-brand-video--iframe')
function playVideo () {
 if (button) {
 button.classList.add('video-poster--hidden')
 iframe.src = iframe.getAttribute('data-src')
 }
}
if (button)
 button.addEventListener('click', playVideo, false)
Ethan Bierlein
15.9k4 gold badges59 silver badges146 bronze badges
asked Apr 5, 2016 at 10:24
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

querySelector can return null. So while you are checking button, you aren't checking for iframe. You will possibly get Assigning property src to undefined or something like that.

classList is one of the newer properties. If you see your code being used in older browsers, you should watch out. Check the compatibility table for support.

A practice used by jQuery and other libraries is to use sets. It's where you put results in an array and for each item, operate on it. If no items are on the set, no code executes.

// Use querySelectorAll to get elements. querySelectorAll returns a
// NodeList. To use array methods, we convert it to an array with
// slice.
const buttons = Array.prototype.slice.call(document.querySelectorAll('.js-brand-video--thumbnail'));
const iframes = Array.prototype.slice.call(document.querySelectorAll('.js-brand-video--iframe'));
// forEach runs the callback for each item in the array. If no items
// reside, no loop runs, therefore no code executes.
button.forEach(function(button){
 button.addEventListener('click', function(){
 button.classList.add('video-poster--hidden')
 iframe.forEach(function(iframe){
 iframe.getAttribute('data-src');
 }); 
 }, false)
});
answered Apr 5, 2016 at 17:21
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.