Ensure that newly added elements are aligned with the settings of the slide's

I've encountered an issue with my jQuery slider that affects a div's CSS on slide. Everything works as expected, except when I add a new div, the settings from the slider aren't applied to the new div until the slider is moved again.

HTML

<div class="inputWrap hidden">
  <input class="inputNumber" type="text" value="5">
  <div class="slider"></div>
</div>

<div class="boxout">
  <div class="box"></div>
</div>

<div class="add">
  add box
</div>

CSS

.boxout {

width: 200px;
height: 200px;
}

.box {

width: 10%;
height: 10%;
background: black;
}

JQUERY

$(".slider").slider({
  min: 0,
  max: 10,
  slide: function(event, ui) {
    console.log("slide", ui);
    $(".box").css("width", 10 + ui.value * 2 + "%");
    $(this)
      .parent()
      .find(".inputNumber")
      .val(ui.value);
  },
  create: function(event, ui) {
    $(this).slider(
      "value",
      $(this)
        .parent()
        .find(".inputNumber")
        .val()
    );
  }
});

var slider = $(".slider");
slider
  .slider("option", "slide")
  .call(slider, null, { value: slider.slider("value") });

$(".add").click(function() {
  $(".boxout").append('<div class="box"></div>');
});

FIDDLE

This setup works perfectly, but when adding a new div, it doesn't receive the same styling as the original box until the slider is interacted with again.

http://jsfiddle.net/or5fhsvh/1/

Your assistance is greatly appreciated.

Answer №1

If you want to achieve your desired outcome, it is necessary to adjust the click function for the .add class.

$(".add").click(function() {
 var slideValue = parseInt($('.inputNumber').val());
 var boxWidth = (10+(slideValue*2)) + '%';
 $(".boxout").append('<div class="box" style="width:'+boxWidth+'"></div>');
});

This function retrieves the slider value, calculates the required box width, and adds a new box in the user interface accordingly. This ensures that the width of all boxes remains consistent based on the slider values without needing adjustments to the slider itself.

You can test this functionality on JSFIDDLE

Answer №2

The function for adding blocks in your code only creates one block, but it does not apply any styles to it. On the other hand, all the existing blocks have their width overridden by inline styles.

To address this issue, you can modify your add function like so:

$(".add").click(function() {
    let additionalStyle = 'width: ' + $(".box")[0].style.width;
    $(".boxout").append('<div class="box"' + additionalStyle + '></div>');
});

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

Increase the options available in the dropdown menu by adding more selected items, without removing any already selected

I came across this code on the internet http://jsfiddle.net/bvotcode/owhq5jat/ When I select a new item, the old item is replaced by the new item. How can I add more items without replacing them when I click "dropdown list"? Thank you <select id=&qu ...

Is it feasible to utilize Google Calendar API for JavaScript through npm install? Alternatively, can the Google Calendar API be utilized for Node.js in the browser within Next.js?

Looking to integrate the Google Calendar API as a library in your Next.js project without using _document.tsx? I have explored two potential approaches for achieving this: Utilize the google calendar api for JavaScript by installing it via npm Use the goo ...

Verify the presence of a specific number of images, and store them in an array

Currently, I am attempting to utilize jQuery to determine if an image exists within my domain, in order to then store them in an array. Below is the code I am using: jQuery(document).ready(function($) { var images = new Array();    var flag = true; ...

Cease making commitments or declarations

I am currently working on validating an image using an API. I have implemented promises and want the execution to stop and call a function if the API check fails. Here is my code: The function for calling the promises: checkPhotos(options,formData, "fr ...

Ways to identify when a file download has finished with the help of javascript

let pageUrl = "GPGeneration_Credit.ashx?UniqueID=" + __uniqueId + "&supplierID=" + supplierID + "&CreditID=" + OrderIds; window.open(pageUrl); // Want to check if the file download is complete and then refresh the page location.r ...

Direct all paths to the base path "/" using Express

Is there a way to redirect all URLs containing "/something" in Express to the base path "/:=", while still maintaining additional paths to their respective pages? For instance, I would like to implement the following redirects: "/something" redirects to ...

Conceal the div element when located beneath an ordered list with a designated

I need help hiding the display of comment information if it is a child comment. Below is my attempt to hide the div with the id "info" if the "ol" element has a class of "children". If you have another method for hiding the div when the comment is a chil ...

Customize Link Appearance Depending on Current Section

Looking for a way to dynamically change the color of navigation links based on which section of the page a user is currently viewing? Here's an example setup: <div id="topNav"> <ul> <li><a href="#contact">Contac ...

The workings of the toString() function within Objects

Recently while delving into a book on Js, I stumbled upon the intriguing topic of Object to primitive conversion. The author made an interesting point in the book: For historical reasons, if toString or valueOf returns an object, there’s no error, but ...

Incorporate a Background Image, which is linked to a website URL, by utilizing an external CSS file within

I am struggling to incorporate an external CSS file (specifically a background image from a URL) into my HTML document. I have successfully applied internal CSS, so the issue is not with the website link. Despite reviewing similar posts addressing comparab ...

Looking for assistance in identifying errors within jQuery or php code on a Wordpress site

I'm struggling to identify the error in my code, especially since it involves multiple languages. Initially, I enqueue the script that needs to be executed and then I utilize wp_localize_script in the main function file of the plugin like this: // A ...

Unable to properly vertically center multiple divs within a parent div and align their elements vertically within them

I'm diving into the world of HTML/CSS and grappling with various concepts. My goal is to vertically align 2 divs within a larger div, as well as center the contents within those divs. HTML: <html> <head> <link rel="stylesheet" typ ...

Type of Data for Material UI's Selection Component

In my code, I am utilizing Material UI's Select component, which functions as a drop-down menu. Here is an example of how I am using it: const [criteria, setCriteria] = useState(''); ... let ShowUsers = () => { console.log('Wor ...

Tips for inputting information without redundancy after selecting a specific designation

I'm experiencing a challenge with this code as it repeats when already chosen. My goal is to add data in the database once something has been selected. When I click on spin, the randomizer will choose a name and update their status to "done". Subsequ ...

What could be the reason behind the link only functioning properly on macOS?

I tried accessing a link that works perfectly on Chrome, Safari, and Firefox on MacOS, but when I try to access it from Windows or Android, I get a 404 error in the browser. Here is an example link: This link is part of an m3u8 file, which can be accesse ...

Using JavaScript to parse JSON and set the value of a DatePicker

I have a text input field in my .cshtml page which is a Date type field. <div class="form-group"> <label for="comments">ETA:</label> <input class="form-control text-box single-line" data-val="true" id="MilestoneETAEdit" name ...

Persisting Big IndexedDB in the Browser

As we embark on the development of a Line of Business (LOB) HTML5 web application, our key objective is to ensure that the application has offline capabilities. Our plan involves retrieving a substantial amount of SQL data from the server and storing it in ...

What is the process for reverting back to a previous version using n (Node Version Manager)?

After installing n(tj/n) to manage my node versions, I installed Node version 14.6 which automatically became the active version. When I tried to switch back using the n command, it only displayed the version I installed with n. Is there a way to switch b ...

In Production environment, v-model triggers a ReferenceError

My Vue View includes the following code: <script setup> import Overwrite from "../components/Overwrite.vue"; </script> <template> <div> ... <textarea v-model="text" cols="99" rows=&qu ...

What advantages does withStyles offer that surpasses makeStyles?

Is there a distinct purpose for each? At what point is it more suitable to utilize withStyles instead of makeStyles? ...