Ensure that the div remains within the viewport

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Title</title>
</head>

<body>
    <div class="videoPop">
        <div class="point"></div>
        <iframe width="440" height="245"
            src="https://www.youtube.com/embed/fj984wXo3O8?autoplay=1&controls=0&disablekb=1&modestbranding=1&rel=0&loop=1'
            frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope">
        </iframe>
    </div>
    <script>
        window.onload = function () {
            var bsDiv = document.querySelector(".videoPop");
            var x, y;
            window.addEventListener("mousemove", function (event) {
                x = event.clientX;//-217
                y = event.clientY - 165;//-280
                if (typeof x !== "undefined") {
                    bsDiv.style.left = x + "px";
                    bsDiv.style.top = y + "px";
                }
            }, false);
        }
    </script>
    <style>
        .videoPop {
            background-color: #3b3b3b;
            border-radius: 0px;
            position: fixed;
            border-radius: 10px;
            width: 440px;
            height: 245px;
            z-index: 200;
            border: 5px solid #3b3b3b;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }

        .videoPop:after {
            content: '';
            position: absolute;
            top: 100%;
            left: 55%;
            margin-left: -55px;
            width: 0;
            height: 0;
            border-top: solid 30px #3b3b3b;
            border-left: solid 30px transparent;
            border-right: solid 30px transparent;

        }


        .videoPopLoading {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 50px;
        }

        iframe {
            border-radius: 5px;
        }
    </style>
</body>

</html>

The YouTube video within the div element follows the user's cursor as it plays. However, I prefer for the video to remain within the boundaries of the window innerHeight and innerWidth, sticking without extending beyond while continuing to follow the cursor until necessary.

This functionality is achieved using pure JavaScript, without utilizing JQuery or other libraries.

https://i.stack.imgur.com/XEJRE.png

Answer №1

To determine the maximum and minimum x and y values, use this method:

window.onload = function() {
  var bsDiv = document.querySelector(".videoPop");
  const divWidth = bsDiv.clientWidth;
  const divHeight = bsDiv.clientHeight;
  const windowWidth = window.innerWidth;
  const windowHeight = window.innerHeight;
  var x, y;
  window.addEventListener("mousemove", function(event) {
    x = Math.max(event.clientX, divWidth / 2); //-217
    y = Math.max(event.clientY - 165, divHeight / 2); //-280
    x = Math.min(x, windowWidth - divWidth / 2);
    y = Math.min(y, windowHeight - divHeight / 2);
    if (typeof x !== "undefined") {
      bsDiv.style.left = x + "px";
      bsDiv.style.top = y + "px";
    }
  }, false);
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Title</title>
</head>

<body>
  <div class="videoPop">
    <div class="point"></div>
    <iframe width="440" height="245" src="https://www.youtube.com/embed/fj984wXo3O8?autoplay=1&controls=0&disablekb=1&modestbranding=1&rel=0&loop=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope">
        </iframe>
  </div>
  <style>
    .videoPop {
      background-color: #3b3b3b;
      border-radius: 0px;
      position: fixed;
      border-radius: 10px;
      width: 440px;
      height: 245px;
      z-index: 200;
      border: 5px solid #3b3b3b;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    
    .videoPop:after {
      content: '';
      position: absolute;
      top: 100%;
      left: 55%;
      margin-left: -55px;
      width: 0;
      height: 0;
      border-top: solid 30px #3b3b3b;
      border-left: solid 30px transparent;
      border-right: solid 30px transparent;
    }
    
    .videoPopLoading {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 50px;
    }
    
    iframe {
      border-radius: 5px;
    }
  </style>
</body>

</html>

Answer №2

updated

if (typeof x !== "undefined" && x -225 > 0 && y -127 > 0 && x < window.innerWidth -225 && y < window.innerHeight -127)

with the following code:

<!DOCTYPE html>
<html lang="en>

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0>
    <meta http-equiv="X-UA-Compatible" content="ie=edge>
    <title>Title</title>
</head>

<body>
    <div class="videoPop>
        <div class="point></div>
        <iframe width="440" height="245"
            src="https://www.youtube.com/embed/fj984wXo3O8?autoplay=1&controls=0&disablekb=1&modestbranding=1&rel=0&loop=1"
            frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope">
        </iframe>
    </div>
    <script>
        window.onload = function () {
            var bsDiv = document.querySelector(".videoPop");
            var x, y;
            window.addEventListener("mousemove", function (event) {
                x = event.clientX;//-217
                y = event.clientY - 165;//-280
                if (typeof x !== "undefined" && x -225 > 0 && y -127 > 0 && x < window.innerWidth -225 && y < window.innerHeight -127) {

                    bsDiv.style.left = x + "px";
                    bsDiv.style.top = y + "px";
                }
            }, false);
        }
    </script>
    <style>
        .videoPop {
            background-color: #3b3b3b;
            border-radius: 0px;
            position: fixed;
            border-radius: 10px;
            width: 440px;
            height: 245px;
            z-index: 200;
            border: 5px solid #3b3b3b;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }

        .videoPop:after {
            content: '';
            position: absolute;
            top: 100%;
            left: 55%;
            margin-left: -55px;
            width: 0;
            height: 0;
            border-top: solid 30px #3b3b3b;
            border-left: solid 30px transparent;
            border-right: solid 30px transparent;

        }


        .videoPopLoading {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 50px;
        }

        iframe {
            border-radius: 5px;
        }
    </style>
</body>

</html>

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 acceptable to duplicate and replace content directly from the Google Inspector tool?

As I work on creating a new woocommerce checkout page, I encountered some issues. My approach to extracting code from woocommerce involved inspecting the Code and copying it directly into my checkout file at /woocommerce/checkout/checkout.php. Is this met ...

Identifying sluggish GPU performance on a mobile device using three.js: A guide for developers

My game runs extremely slow on older mobile devices like the Samsung Galaxy S4 and iPhone 5 when shadows are enabled. However, when shadows are turned off, performance improves significantly. Is there a way to detect a slow GPU in order to disable sh ...

HTML/CSS - Enhances user experience by zooming in on select tag when tapped on mobile devices

I am experiencing an issue with a select menu on mobile devices. Whenever I tap on the menu, it seems to zoom in slightly. Is there a particular -webkit property causing this behavior? How can I prevent the screen from zooming when I tap on the select me ...

Utilize JavaScript/jQuery to check for upcoming deadlines in a SharePoint 2013 list

I need to check if an item is due based on its date. When a user creates an item with a date in the format MM/DD (e.g., 06/15), I want to determine if that date falls within the next 30 days, turning it red, within the next 60 days, turning it orange, or g ...

Show a concealed dropdown menu within a CSS grid column utilizing clip-path styling

Working on a Django admin header that makes use of CSS grid to create two columns. I have added a JavaScript dropdown effect to the user icon for displaying options like "Change Password" and "Log Out". However, encountering an issue where the dropdown rem ...

Load data from a file into a dropdown menu using node.js

Exploring the realm of front end development on my own has been quite a challenge. I am currently struggling with the concept of populating a drop down box with data from a file. While utilizing node and JavaScript, I have decided to stick to these techn ...

Using CSS3, you can apply multiple backgrounds to an unordered list with one set

Currently, I am in the process of working on a unique Wordpress template. One of the challenges I am facing is figuring out how to incorporate three background images for each <li> element in the dynamically generated navigation menu. Here are two ex ...

Ways to modify the cursor of a disabled ImageButton on an ASP.Net webpage

Within a ListView, I have dynamically generated ImageButtons. If an image does not have a link, I want to make it disabled. In the ItemDataBound event, I attempted the following approach: img.Enabled = False img.DescriptionUrl = "javascript:void(0);" img. ...

Showing JSON data as a table in an HTML format

After receiving the JSON String from the server as a response, which can be viewed here, I've implemented the following Jquery Code: function loadCategories() { $.ajax({ type: "POST", url: "/Services/ControllerService. ...

transmitting information using dataURL

Hey there! So I've got this code that does a neat little trick - it sends a dataURL to PHP and saves it on the server. In my JS: function addFormText(){ $('body').append('<input type="hidden" name="img_val" id="img_val" value="" /& ...

Encountering an issue while updating information following the migration to vue-chartjs 4

I recently upgraded from vue-chartjs version 3 to version 4. I successfully migrated my LineChart component by updating the template section and removing the draw method calls. This component is utilized for two separate charts. However, when I close the ...

"Make sure to tick the checkbox if it's not already selected,

Could use some assistance with traversing and logic in this scenario. Here is the logic breakdown: If any checkbox in column3 is checked, then check the first column checkbox. If none in column 3 are selected, uncheck checkbox in column1. If column1 ...

Using AJAX to send data to the server in jQuery

Currently, I have an AJAX request implemented on my webpage. I am exploring methods to detect when an AJAX call is initiated within the page using jQuery or JavaScript. Is there a way to identify or trigger a function upon the initiation of an AJAX reques ...

Receiving a null value when attempting to access the ids of dynamically created HTML elements using JavaScript

Encountering issue with accessing ids of dynamically generated HTML elements using javascript In my current project, I am attempting to dynamically alter the ids of div elements and remove buttons that are appended to the parent div. The desired functiona ...

Isn't AJAX all about the same origin policy?

Despite my confusion surrounding the same domain origin policy and jQuery AJAX, I have noticed that when I make a GET request to a URL using jQuery, I am able to successfully retrieve the results. This goes against what I understood about the restriction ...

Troubleshooting Problem with Custom Class Buttons in Angular Material

Recently, I've been working on creating a custom class for angular material buttons. However, I encountered an issue where the button fades out or turns white when I click on it and then navigate away from the browser window (minimize it or activate a ...

Shifting an image within a div using HTML5 and CSS3

I am wondering how to position the image 50px from the top and 50px from the left within the div. Should I use padding for this? <header> <img src="logo.png" alt="" /> </header> header { width... height: background: (url) } ...

Issue with DIV height in Internet Explorer occurs only when application is accessed using server name

Encountering a unique issue specific to IE (confirmed in v8 and v9). When utilizing jquery to determine the height of a div: $('#sys_MainPage').height() In Chrome, Firefox, and when accessing using the IP address, this code returns around 26 ...

Unlock the secrets of recovering deleted data from a text area in Kendo UI Angular

Currently working with Kendo UI for Angular, I need to capture deleted content and remove it from another text area within the same component. My project is using Angular-13. I'm stuck on how to accomplish this task. Any suggestions would be greatly ...

The router is unable to direct when an item is clicked

I am encountering an issue with my routing setup - when I click on an item in the list-item component, it does not successfully route to the detail-component. Here is a glimpse of my source code: product-list.component.html: <h1>Product List Compon ...