What is the best way to position a rectangle on top of a div that has been rendered using

I recently started using a waveform display/play library known as wavesurfer. Within the code snippet below, I have integrated two wavesurfer objects that are displayed and positioned inside div elements of type "container". My goal is to position my own rectangle over one of these wavesurfer objects and then control its position using Javascript.

One issue I am encountering is avoiding the use of absolute coordinates with respect to the browser window. Instead, I aim to utilize relative coordinates based on the position within the wavesurfer object itself. Moreover, despite placing the rectangle within the same div container as the waveform, it is not overlaying the waveform as desired.

Although this may seem like a basic question regarding overlaying shapes on top of visuals such as pictures, I have been unable to find a suitable solution that works for the specific waveform objects in my project.

var wavesurfer = WaveSurfer.create({
  container: "#waveform",
  waveColor: "darkorange",
  progressColor: "skyblue",
  interact: false
});

wavesurfer.load("https://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3");


var wavesurfer2 = WaveSurfer.create({
  container: "#waveform2",
  waveColor: "silver",
  progressColor: "gainsboro",
  interact: false
});

wavesurfer2.load(  "https://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3"
);
<body>
  <script src="https://unpkg.com/wavesurfer.js"></script>
  <script src="https://unpkg.com/wavesurfer.js/dist/wavesurfer.min.js"></script>
  <script src="https://unpkg.com/wavesurfer.js/dist/plugin/wavesurfer.regions.min.js"></script>
  
<div class="container" style="display: flex">
  <div id="waveform" style="width:60%"></div>
</div>

<div class="container" style="display: flex">
  <div id="waveform2" style="width:60%"></div>
</div>

  <div>
    <input type="range" id="slider" name="range_slider" min="0" max="11">
    <label for="range_slider">Range Slider</label>
  </div>
  
  
  <div id="selector">
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <rect x="10" y="10" width="50" height="100" stroke="black" stroke-width="5" fill="none" />
      </svg>
    </div>

Answer №1

One effective method is using the getBoundingClientRect function to retrieve the offset height and left position of a specific element. By leveraging these values, it becomes simple to accurately position any element in relation to them.

For further details, please refer to: https://example.com/reference-52477551

Answer №2

Another method to consider is adding a pseudo element to each waveform, allowing for positioning in percentage terms relative to the width of the waveform.

In this code example, a border is used to draw a rectangle around the pseudo element, but an image could also be utilized for a more complex shape if needed.

To simplify styling of these elements, a class "waveform" is introduced.

var wavesurfer = WaveSurfer.create({
  container: "#waveform",
  waveColor: "darkorange",
  progressColor: "skyblue",
  interact: false
});

wavesurfer.load("https://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3");


var wavesurfer2 = WaveSurfer.create({
  container: "#waveform2",
  waveColor: "silver",
  progressColor: "gainsboro",
  interact: false
});

wavesurfer2.load("https://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3");
.waveform {
  position: relative;
}

.waveform::before {
  content: '';
  width: 20px;
  height: 50px;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 3;
  border: solid 5px;
  left: var(--left);
}

#waveform {
  --left: 60%;
}

#waveform2 {
  --left: 8%;
}
<body>
  <script src="https://unpkg.com/wavesurfer.js"></script>
  <script src="https://unpkg.com/wavesurfer.js/dist/wavesurfer.min.js"></script>
  <script src="https://unpkg.com/wavesurfer.js/dist/plugin/wavesurfer.regions.min.js"></script>

  <div class="container" style="display: flex">
    <div id="waveform" class="waveform" style="width:60%"></div>
  </div>

  <div class="container" style="display: flex">
    <div id="waveform2" class="waveform" style="width:60%"></div>
  </div>

  <div>
    <input type="range" id="slider" name="range_slider" min="0" max="11">
    <label for="range_slider">Range Slider</label>
  </div>

CSS variables are employed here to determine the position along a waveform where the selector should be placed. To adjust this for a specific waveform element, simply set the style property like so: element.style.setProperty('--left', '60%');

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

Error: authentication failed during npm installation due to an incorrect URL

After executing npm install @types/js-cookie@^2.2.0, an error occurred: npm install @types/js-cookie@^2.2.0 npm ERR! code E401 npm ERR! Unable to authenticate, need: Basic realm="https://pkgsprodsu3weu.app.pkgs.visualstudio.com/" npm ERR! A com ...

The GET method is designed to automatically eliminate any trailing whitespace in the

Whenever I utilize the GET method to transmit a text to the server, like 'abc ', I notice that the whitespace characters at the end are always removed. As a result, the server receives 'abc' instead of 'abc ' My question is w ...

What is the best way to utilize a JavaScript variable as a background within an inline style sheet?

I have a fun project for this evening - I am trying to make my website load a different background image every time the page is refreshed. Earlier on in this project, I managed to make the background interact with window size and screen resolution similar ...

How can we add styles to text entered into a form input field in a targeted way?

Is there a way to apply styling to the second word entered into a form input text field after the user hits "enter" and the data is output? In this scenario, the text always follows the format of 3 numbers, followed by a space, and then a name. For examp ...

Prevent the use of the + or - symbols within the body of a regular expression when

function validateNumberInput(){ userInput = document.getElementById('txtNumber').value; var numberPlusMinusRegex = /^[\+?\-?\d]+$/g; if (userInput.match(numberPlusMinusRegex)) { alert('Vali ...

Using JavaScript to display content on the screen

As a newcomer to Javascript, I'm looking for a way to display my variable on the webpage without utilizing <span> or innerHTML. var pProductCode = $('[name=pProductCode]').val(); $('input[id*="_IP/PA_N_"]').each(function(i){ ...

Tell me about the CSS ruby-align characteristic

While browsing online, I stumbled upon a reference to the ruby-align property that piqued my interest. After searching on w3schools for some examples, I was surprised to find no mention of it anywhere. I remembered that Ruby is a newer tag in HTML5 and de ...

Substitute the <body> tag with a different tag

I am attempting to use the following code to replace the <body> tag on a page with <body id="khanqah"> echo str_replace("%body%", "khanqah", "<body id='%body%'>"); Although it adds <body id="khanqah"> to the page, the or ...

Is using async/await with setState() in React.js the best approach for handling asynchronous operations?

By utilizing async and prevState, I found a solution to console.log the correct state of the page immediately after updating it. As I delved into backend development, I took the time to understand how async operations function. This led me to experiment w ...

Refresh website-wide variables after a post has been made

Within my index.js file, I am rendering a page with global variables. router.get('/index', function(req, res, next) { res.render('index', { title: 'RLH', countNumber: countNumber, countReleased: countReleased, coun ...

Utilizing Angular to integrate with an external API

I have encountered an issue while trying to connect to the Expedia API. In order to do so, I need an API key and ID. Initially, I utilized JSONP for this connection but ran into a bug causing problems. Additionally, storing my API key in JavaScript poses ...

JQuery Mobile fails to apply consistent styling to user input check items within a list

I have successfully implemented the functionality to add user input items to a checklist. However, I am facing an issue where the newly added items are not adhering to Jquery Mobile's styling. Here is a screenshot showcasing the problem: Below is th ...

What is the best way to detect the window scroll event within a VueJS component?

Looking to capture the window scroll event in my Vue component. This is what I have attempted so far: <my-component v-on:scroll="scrollFunction"> ... </my-component> I have defined the scrollFunction(event) in my component methods, but it ...

The PhpStorm/JavaScript expression statement doesn't involve assignment or function call

I am striving to enhance the cleanliness of my method. Based on the value of an integer number, I am generating different date formats, resulting in the following: getRanges() { var currentDate = new Date(); //This can ...

Creating a custom math formula using a combination of Javascript and PHP

Is it possible to apply a math formula from another variable or database? var x = 7; var formula = '+'; var y = 10; By this, I mean that the variables should output = 17 (7 + 10); How can we implement this formula using Javascript or PHP? ...

Organizing Perspectives in AngularJS

Transitioning from Backbone to AngularJS, I am embarking on creating my first application with the latter. To kick things off, my initial task involves migrating an existing backbone application to AngularJS. This application features a main view housing ...

Initiate activity when link is clicked

I am currently in the process of developing a website that includes 5 divs. <div class="one"></div> <div class="two"></div> <div class="three"></div> <div class="four"></div> <div class="five"></div ...

Guide on transforming Color to HTML color with .NET Standard 2.0

How can I convert a color to HTML color in .NET Standard 2.0? Thank you. Is there a way to achieve the same functionality in .NET Core? System.Drawing.ColorTranslator.ToHtml(color); Or is this only available in DotNet Framework? ...

Populating Dropdown list with values based on input provided in Textbox

Can you assist me in finding the solution to this issue? I have a TextBox and a DropDown list. For example, if I type "Anu" into the textbox, I want it to populate the dropdown list based on the text entered. How can I achieve this? I am working with vb. ...

Making an API request using jQuery

I am currently working on creating a .js file that will send data to an external API, wait for a response, and then interpret the results. The external API I am using is XML-based and requires an HTTPS Post request with the XML content in the body (content ...