Seeking a more streamlined approach to coding in Javascript

Is there a more efficient way for me to implement the toggleFullscreen() function? Currently, I am redundantly setting the style rules for each browser, which seems unnecessary.

function toggleFullScreen() {   
  var elem = document.getElementById("video_container");
  var db = document.getElementById("defaultBar"); 
  var ctrl = document.getElementById("controls");

  if (!document.fullscreenElement &&    // using alternative standard method
      !document.mozFullScreenElement && !document.webkitFullscreenElement) {  // using current working methods
    if (document.documentElement.requestFullscreen) {
          db.style.background ='red';
          ctrl.style.width = '50%';
          ctrl.style.left = '25%';
          elem.requestFullscreen();
        } else if (document.documentElement.mozRequestFullScreen) {
          db.style.background ='red';
          ctrl.style.width = '50%';
          ctrl.style.left = '25%';
          elem.mozRequestFullScreen();
        } else if (document.documentElement.webkitRequestFullscreen) {
          db.style.background ='red';
          ctrl.style.width = '50%';
          ctrl.style.left = '25%';
          elem.webkitRequestFullscreen();
        }
  } else if (document.exitFullscreen) {
        db.style.background ='yellow';
        ctrl.style.width = '100%';
        ctrl.style.left = '0';        
        document.exitFullscreen();
        }
        else if (document.mozCancelFullScreen) {
        db.style.background ='yellow';
        ctrl.style.width = '100%';
        ctrl.style.left = '0'; 
        document.mozCancelFullScreen();
        }
        else if (document.webkitCancelFullScreen) {
        db.style.background ='yellow';
        ctrl.style.width = '100%';
        ctrl.style.left = '0';
        document.webkitCancelFullScreen();
        } 
}

Answer №1

the fullScreen style rules kick in immediately upon page load.

This behavior is caused by the following code snippet:

full.addEventListener('click', toggleFullScreen(), false);

The issue lies in the fact that toggleFullScreen() is executed right away and its return value is passed to addEventListener. To correct this, the code should be:

full.addEventListener('click', toggleFullScreen, false);

This modification ensures that the function reference is passed instead of its return value.

Optimization

By utilizing the || operator, you can simplify the existing conditions significantly.

var fullScreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement;

if (fullScreenElement) {
  var requestFullScreen = document.documentElement.requestFullscreen || document.documentElement.mozRequestFullScreen || document.documentElement.webkitRequestFullscreen

  db.style.background ='red';
  ctrl.style.width = '50%';
  ctrl.style.left = '25%';
  requestFullScreen.call(elem);
} else {
  var exitFullScreen = document.exitFullscreen || document.mozCancelFullScreen || document.webkitCancelFullScreen;

  db.style.background ='yellow';
  ctrl.style.width = '100%';
  ctrl.style.left = '0';        
  exitFullScreen.call(document);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to have the background scroll downward while keeping some content centered in place at all times?

Attempting to achieve the following effect in JavaScript, HTML, and Sass: When scrolling down the page, the layers (ground, sky, space, etc.) move downward The content (a rocket flying in the sky) stays centered on the screen and will move horizontally l ...

When using State.go(), the url in the address bar will update, but the HTML view will not be refreshed

Encountering an issue while working on Ionic with AngularJS, specifically with the routing system when attempting to create a login page. In the controller section of the code, I am trying to navigate to a welcome page called 'dash' using state.g ...

Implementing a text field to initiate an Ajax request

I need help with triggering my Ajax function whenever a text field is changed. As someone who is new to Ajax, I'm not sure if this is even possible. Any guidance on how to achieve this would be greatly appreciated! Html <form> <a>Ent ...

When a variable is used, the .sort() method does not effectively organize the elements

When working with Nodejs and mongoose queries, I encountered an issue with using the .sort() method dynamically based on user input. While it works fine when hardcoded, I want to use a variable to determine the sorting order. However, when attempting to do ...

Update the style of the legend from bars to a line chart in chart.js version 2.4.0

https://i.sstatic.net/BXcXj.pngI'm currently using chart.js version 2.4.0 for displaying graphs, and I'm having trouble changing the legend style from bar to line. Is there a way to switch the legend display from bar to line in chart.js? Here i ...

The function(result) is triggered when an http.get request is made

Can anyone help me figure out why my function is jumping after completing the request? It seems to be skipping over .then(function(result){ }. I suspect that the issue might be related to the <a> element with an onclick attribute containing an href ...

Using keyframes for flexbox animation in Safari

What could be causing the issue with flex keyframes not working in Safari while functioning properly in other browsers? <div class="a"> <div class="b"></div> </div> .a { height: 200px; display: flex; } .b { flex:0 1 50% ...

Running Javascript based on the output of PHP code

I have been working on my code with test.php that should trigger some Javascript when my PHP code, conditional.php, detects input and submits it. However, instead of executing the expected "Do Something in Javascript," it outputs "Not empty" instead. I fin ...

Issue encountered: Unable to load resource - ajax file upload failed due to net::ERR_SSL_BAD_RECORD_MAC_ALERT error

I've implemented an AJAX form file upload using jQuery. After testing my code across multiple computers and browsers, I've encountered an issue on one Windows 8 machine running Chrome where the upload functionality fails with the following error ...

The canvas is being expanded by utilizing the drawImage method

Ensuring the correct size of a <canvas> element is crucial to prevent stretching, which can be achieved by setting the width and height attributes. Without any CSS applied other than background-color, I am faced with an unusual issue. Using ctx.draw ...

The angularjs response data is mysteriously missing from the console display

I am struggling with the code below, as the data is not showing in the console log. I am new to Angular and would appreciate some help on how to display the data in HTML. this.$http.get(properties.client+'/123') .then(response => { ...

Problems encountered with dragging elements in Firefox

Is there a reason why an image may not be draggable in Firefox even when the draggable="true" attribute is set? I am working on a JavaScript image swapping script and encountering difficulties with drag-and-drop functionality specifically in Firefox. While ...

Distinguishing the time gap between two dates in AngularJS

My application consists of an API built using Spring Boot and a view created with AngularJS. The app retrieves a report indicating when an incident started and ended, with examples like startdate(2015-12-01T08:19:00.000Z) and enddate(2015-12-06T02:59:00.00 ...

XMLHttpRequest is unable to load due to the absence of the 'Access-Control-Allow-Origin' header on the requested resource

I am currently working on an Angular application with a .NET Core web API. The initial request is made to a /token service, but I keep encountering a CORS error despite having it enabled. What could be missing in my setup? :8088/#/home:1 XMLHttpRequest ...

Using Bootstrap to style the <option> element with RGBA colors

Struggling to figure this out and seeking assistance. I have a form using bootstrap where I can apply rgba color for my select tag but not for the options. Select CSS: select { background-color: rgba(0,0,0,0.25) !important; border: 1px solid rgba ...

Is there a way to enable a clickable imagemap area using jQuery?

Example showcasing different behaviors in various browsers (jsfiddle link): <!DOCTYPE html> <html> <head> <title>Browser Behavior Test</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/ ...

The sidebar on the right side of the screen is content to relax beneath my

The positioning of my sidebar is currently below the content on the left side of the page, but I want it to sit beside the content on the right side. I've tried various solutions from similar questions without success. Here is an example of how I woul ...

Tips for making sure your published npm package respects the baseUrl specified in the tsconfig.json file

I am currently developing an npm library using TypeScript. Within our project configuration, we have specified a baseUrl in our tsconfig.json file. "baseUrl": "src", When referencing files within the src directory, we can simply use: src |-folderA ...

A guide on transforming Jonatas Walker's TimePicker into a custom JavaScript class or a versatile jQuery plugin

I came across a timepicker solution on this Stack Overflow answer that I really liked. However, I encountered difficulties trying to implement it in a project where input elements are dynamically created. It seemed like the timepicker required specific han ...

Swap out a component for another using a higher order component (HOC perhaps?)

I have noticed that certain libraries like "framer-motion" in react utilize this syntax, for instance to include an animated H1: <motion.h1> where the h1 tag is enhanced with animations specified in the component's props. What confuses me is ho ...