assigning the browser's width to a variable within an scss file

Is there a way to dynamically set the browser's width as a variable?

I am familiar with @media queries, but I need to calculate the browser's width for a specific purpose.

I attempted using jQuery to achieve this, and it works well with a fixed browser width. However, it fails to update when I resize the browser window.

Here is what I aim to accomplish:

html

<section id="slider">
    <div class="slides">
      <div class="slide">
        <h1>silde 1</h1>
        <p>Lorem ipsum dolor</p>
      </div>
     <div class="slide">
        <h1>silde 2</h1>
        <p>Lorem ipsum dolor</p>
      </div>
    </div> </section>

SCSS

$browser-width: (BROWSER WIDTH HERE) * .75 ;
#slider {
  overflow: hidden;
  position: relative;
  margin: auto;
  width: $browser-width;
  .slides {
    display: block;
    margin: 0;
    padding: 0;
    width: 6000px;
  }
  .slide {
    width: $browser-width;
    display: inline-block;
    float: left;
    text-align: center;
  }
}

As a temporary solution, I implemented the following jQuery code:

$(document).ready(function(){   
  var width = $(window).width() * .75;   
  var $slider = $('#slider');   
  var $slideContainer = $slider.find('.slides');   
  var $slides = $slideContainer.find('.slide');   

  $slider.css("width", width);   
  $slides.css("width", width);

  /* function to make the slider here */ 
});

Setting 'width = 75%' or 'width = 75vw' did not yield the desired result.

Answer №1

Problem solved! I figured out what was causing the issue - using 'vw' as the answer instead worked perfectly. The mistake was in my sliding function.

'margin-left' : '-=' + width

I realized that I needed to include the unit 'vw' like this:

'margin-left' : '-=' + width + "vw"

It's important not to forget specifying units in your code... lesson learned!

If you're curious, here is the sliding function:

'use strict';


$(document).ready(function(){

  var width = 75;
  var animationSpeed = 1000;
  var pause = 1000;
  var currentSlide = 1;

  var $slider = $('#slider');
  var $slideContainer = $slider.find('.slides');
  var $slides = $slideContainer.find('.slide');

  var interval;


  function startSlider(){
    interval = setInterval(function() {
      $slideContainer.animate({'margin-left' : '-='+width + "vw"}, animationSpeed, function(){
        currentSlide++;
        if (currentSlide === $slides.length){
          currentSlide = 1;
          $slideContainer.css('margin-left', 0);
        }

      });

    }, pause);
  }
function stopSlider(){
  clearInterval(interval);
}

$slider.on('mouseenter', stopSlider).on('mouseleave', startSlider);

startSlider();

});

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

Best practice for sending a Facebook token securely between client and server

I'm facing a dilemma on how to securely transfer a user's Facebook token from their client to my server. Currently, I have the following approach in mind: The user accesses a webpage and logs in to Facebook; Facebook token is obtained; User&apo ...

Pass function A as a prop, then trigger a different function when the child function calls A

Apologies for the uninformative title; I struggled to come up with a suitable one regarding my issue. I have a question concerning React code. My Child component receives the onValueChanged function as a prop. This function was initially passed down to th ...

Utilizing Jquery's replacewith function to extract and read the id value

In this script, changing the dropdown list populated with opt1/opt2 triggers an alert displaying the ID as 'drop'. However, when I click on the 'clickme' text entry box, it transforms into a new dropdown. Yet, there is no alert issued ...

The width of the plotbands on the yAxis of a stacked bar graph is adjusting as the series are dynamically toggled,

https://ibb.co/h7tmwtr https://ibb.co/syRTyPG For the first time, I have included 5 plot bands which looked great. However, when I added a series and toggled it on a stacked bar graph, the plot bands' width started increasing. I want to maintain the ...

The div that scrolls gracefully within its boundaries

Currently, I am working on a task that involves a div containing images that need to be scrolled left and right. I have successfully implemented the scrolling functionality using jQuery. However, I now face the challenge of ensuring that the content stays ...

Ways to adjust the size or customize the appearance of a particular text in an option

I needed to adjust the font size of specific text within an option tag in my code snippet below. <select> <?php foreach($dataholder as $key=>$value): ?> <option value='<?php echo $value; ?>' ><?php echo ...

Ajax request returns a 500 error, yet the request successfully executes

I have set up an API controller to manage an ajax request. Each time the Ajax request is sent from the script below, I encounter a 500 error: POST http://localhost:58463/api/Reservations 500 (Internal Server Error) jquery-2.1.0.min.js:4 l.cors.a.crossDomai ...

What causes old data to linger in component and how to effectively clear it out

Fetching data from NGXS state involves multiple steps. First, we define the state with a default list and loading indicator: @State<CollectionsStateModel>({ name: 'collections', defaults: { collectionList: [], (...), isListLoading: true, ...

"Exploring the power of Vue3's composition API in managing the

Trying to implement an accordion component in Vue 3, but encountering a strange comparison issue. I'm attempting to execute a function within the accordionitem - specifically the toggle operation. However, despite numerous attempts, I am unable to mo ...

Unfortunately, the header and footer are not lining up correctly with the main body on our mobile site

I've been tasked with creating a fully responsive website, but I'm encountering difficulties with the mobile design. Specifically, when I switch to mobile dimensions like an iPhone 12, the header and footer don't line up properly with the ma ...

Introducing React JSX via a nifty bookmarklet

Looking to convert code found in an HTML file into a bookmarklet? Here's the code snippets involved: <script src="JSXTransformer-0.13.3.js"></script> <script src="react-0.13.3.js"></script> <script type="text/jsx;harmony=tr ...

What is the proper way to handle a 504 response header in an AJAX request using jQuery?

Recently, I encountered an issue with an AJAX call from the client that caught my attention. Here is a snapshot of how it looked: $.ajax({ 'url': '/converter/ajax-make-corrections/', 'data': { ...

Using React.JS: Display Object Map in rendering

I have an object with family information that looks like this: Family: Parent0: BirthPlace: "dsa" Birthday: "2021-01-04" Relationship: "dsa" SurnameAndName: "dasdsa" Parent1: BirthPlace: & ...

A step-by-step guide on rotating a solitary image within HTML

Is there any way to make these three images in my table rotate continuously? I've looked everywhere for a solution but can't find anything. I want the rotation to mimic that of a planet rotating on its axis. Check out this one: BARCELONA <t ...

Arrange three div elements beside each other with the middle column containing two

My challenge involves figuring out how to display 3 divs on a webpage in a specific layout. Currently, I am able to get 2 divs to align next to each other using the float:left property. However, the third div always ends up positioned below the first one ...

Interactive image grid with adjustable description field per image upon selection

My goal is to create a grid of images with a single text field below the grid. This text field should display the description of the image that was last clicked. The grid is implemented using floating divs within a main div, as shown in the code snippet be ...

Tips for making sure a header is consistently at the top of every page during printing

I need help with my website - I have a table that is quite tall and spans across multiple pages when printing. Is there a way to make the header row appear on top of each page when printing? ...

Display a static partial on a webpage using AJAX in Rails 3

So, I have 2 follow/unfollow forms in my Rails code. Here's the first one: <%= form_tag( {:controller => 'profile', :action => 'unfollow_topic' }) do %> <%= hidden_field_tag :topic_id, @topic.id %> <button ...

What is the significance of -= and += operators in JavaScript programming language?

I'm puzzled by the mathematical process behind this JavaScript code, which results in -11. let x = 2; let y = 4; console.log(x -= y += 9) ...

Creating Functional Tabs Using CSS and JavaScript

I've been experimenting with this code snippet, trying to get it to work better. It's still a work in progress as I'm new to this and have only customized it for my phone so far. The issue can be seen by clicking on the Projects and Today ta ...