Is this JavaScript function acceptable?

My dilemma involves a carousel (specifically Owl Carousel) with controls that need to be vertically centered. Due to the structure, I have had to absolutely position the previous and next arrow indicators. Given the responsive nature of the page, their positioning is not fixed as it may change based on different screen sizes. Additionally, the size of these controls can also vary.

https://i.sstatic.net/my7vn.png

To tackle this issue, I devised a function that executes during page load and whenever the window is resized. This function calculates the height of the image within the carousel and the height of the controls, subtracts the latter from the former, divides by two, and sets this result as the margin-top for the controls.

Although my approach works, doubts linger regarding whether or not I am handling all the variables accurately in JavaScript. Is there a specific order in which JavaScript processes statements? My expertise lies more in CSS, so JavaScript has always been somewhat challenging for me.

Is there a more efficient way to write this code?

function centerCarouselControls() {
  var carouselImage = $('.carousel-card > img');
  var carouselControls = $('.owl-nav > div');
  var carouselHeight = carouselImage.outerHeight();
  var controlHeight = carouselControls.outerHeight();
  var controlMargin = (carouselHeight - controlHeight) / 2;
  carouselControls.css('margin-top', controlMargin);
}

$('.carousel-card > img').load(centerCarouselControls);
$(window).on('resize', centerCarouselControls);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I worry that this question might not provide enough detail for this platform and could potentially get flagged. If that's the case, please direct me to a more suitable community where I can seek assistance. Thank you!

Answer №1

On certain browsers, your code functions similarly to Firefox version 51. However, the following code is more comprehensive:

carouselControls.css('margin-top', controlMargin + 'px');

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

The negative z-index is causing issues with my ability to select classes using jQuery

By setting a z-index of -3 for several divs in my background, I thought they wouldn't affect the formatting of elements in the foreground. But now I'm facing an issue where I can't click on those background divs when trying to target them wi ...

How to access and retrieve selected checkbox values using jQuery

<form id="myform"> <input type='checkbox' name='foo[]' value='1'> <input type='checkbox' name='foo[]' checked='true' value='2' > <input type='checkbox' ...

Inexplicably, HighCharts flips its axis when exporting data

I am facing an issue with the display of my Highchart in the web application. While it appears correctly in the browser, the exported chart flips the axis and shows a different image. Below are the options I have configured for my Highchart: var options = ...

Tips for retrieving information from an API and displaying it in a table

I'm struggling to retrieve data (an array of objects) from an API using a Token and display them in a table using Material-UI. However, I keep encountering the following error: Uncaught (in promise) SyntaxError: Unexpected token 'A', "Access ...

I'm looking to send JSON data using jQuery's AJAX method - how can I

I was recently assigned a project with the following instructions: Develop an HTML page that will use our API endpoint to fetch a list of logs from our API logger and display them in a visually appealing grid. The page should automatically make this call e ...

What is the most efficient method for arranging the numbers in a whole number?

Is there a more efficient method than storing the numbers in an array and using .sort() to arrange them? ...

Immersive Elevation Modal Framework

In my Bootstrap modal, I have a plethora of content, such as: https://i.sstatic.net/o6lm4.png However, the bottom of the modal is experiencing an overflow of height like so: https://i.sstatic.net/qlKrl.png I've attempted utilizing the max-height p ...

Steps for transferring an `<li>` element from one `<ul>` to another

<ul id="List"> <li class="li">1</li> <li class="li">2</li> </ul> <ul id="List2"></ul> const items = document.querySelectorAll(".li"); for(var i = 0; i < ...

Issues with JSON data not functioning properly when using file system in JavaScript

When attempting to parse a JSON file, I encountered some errors. The file is located in a directory within my JavaScript file, under the 'fs' in a folder named "recipes." Within this folder, there are 3 JSON files, each representing a separate ob ...

Dealing with an overflow of Redis clients in NextJS: Simplifying the process with just one client

Introduction Hello there! I have developed a new app for a discord web-dashboard and utilized redis as my database. The main Issue Whenever I send an axios request to one of the documents in the api folder, which requires a redis client, a new redis cl ...

Providing both app and io as parameters to a module

Extracted from my server.js: const app = require('express')(); const server = require('http').createServer(app); const io = require("socket.io").listen(server); server.listen(port, function(){ console.log('Server listening at ...

Navigating from child to parent page in Next.js: how can it be done?

Forgive me if this question seems simplistic, I am new to the world of Next.js and React.js. From my understanding, in Next.js, we can organize pages hierarchically, with each xx_page.js file's path serving as its corresponding url route, as noted in ...

When clicking on the side-bar, it does not respond as expected

My website has a menu layout that features a logo on the left and an icon for the menu on the right side. When the icon is clicked, the menu slides in from the right side of the window, and when clicked again, it slides out. However, I am facing two issues ...

Despite using preventDefault and returning false, the user is still being redirected after submitting the form

I'm in the process of trying to send a form using JQuery's .ajax function without having the user redirected upon submission. The form and backend code are both functioning as expected. However, I am encountering an issue when it comes to prevent ...

Sort, Transform, and Condense

In my code snippet, I have a loop that iterates over an array and manipulates the data: $scope.listDeColaboradoresObject.forEach(item => { item.listNmAssunto = $scope.relatorioTotalMensagensRespondidasColab .filter ...

I am experiencing difficulty with Three.js rendering textures from my planet constructor function

I am facing an issue with my function that is supposed to create a 3D object (a planet) using orbital parameters and texture images from a dataset. Strangely, the textures are not rendering when I use StandardMaterial or PhongMaterial, even though they wor ...

Send a POST request to the db.json file containing an object with various attributes

Here is the code snippet I am working with: function createObject(){ let object = { product1 : "Apple", product2 : "Banana", product3 : "Cucumber", product4 : "Duba", product5 : "Emil", product6 : "Fidschi", } return object ...

Is it possible for consecutive json and jsonp requests to fail on Crossrider?

I am currently utilizing crossrider to develop a plugin that works across various browsers. Within my implementation, I have two consecutive AJAX requests (one JSON and one JSONP): The first request involves a JSON call for "login" which sets a brows ...

Localizing Dates in JavaScript

I'm currently dealing with localization and globalization in an ASP.NET application. As I navigate through this process, I am encountering difficulties in getting the Date() function in JavaScript to function correctly based on the user's locatio ...

Azure Chatbot that logs conversations in Webchat whenever the user selects 'none of the above' option

Recently, I've delved into the world of web chat services and embarked on a journey to craft a chat bot using pure JavaScript code that can seamlessly integrate into any HTML file. Despite consulting Microsoft's documentation, I find myself in a ...