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

What causes a new stacking context to be formed when using position: relative without z-index?

After reading this informative piece: When two elements share the same stack level, their layering is determined by their order in the source code. Elements stacked successively are placed on top of those that came before them. And referencing this ar ...

Error: Unable to access property 'fetch' of null (discord.js)

Hey there, I'm running into an issue where it's giving me an error saying that the property 'fetch' doesn't exist. I'm using the Replit database for a balance command in discord.js. You can see the error image here. Here is t ...

Guide to easily uploading an image to Amazon AWS (S3) with Ajax and Jquery in a Rails application

Is there a way for users to easily upload their images directly from the site? I've made progress, but now I'm stuck on uploading the image to the server. How can I resolve this issue? HTML - <div> <div style="height: 80px; position ...

Issue with retrieving query results using node_redis client

I've been struggling with a particular issue that I just can't seem to solve. The problem revolves around not being able to retrieve output values from a Redis query. My setup involves using the node_redis client as the Redis driver for my Node.J ...

Does shouldComponentUpdate returning `true` have the same effect as not having shouldComponentUpdate at all?

Within my React Native component, I have included a blank shouldComponentUpdate shouldComponentUpdate(nextProps, nextState) { } I am aware, from reading this answer, that an empty shouldComponentUpdate function helps in eliminating unnecessary re ...

Determine the id value by selecting spans within a div using jquery

I am looking to extract the id value from the spans. Many thanks, Jean ...

Is there a way to modify the text within a "span" element that directly follows an "i" element using jQuery?

I am attempting to modify the text displayed on a button within a plugin by using jQuery. Here is the outer HTML: <button value="[[3,1,1488182400]]" data-group="2017-02-27" class="ab-hour"> <span class="ladda-label"> <i class="ab-hour ...

What is the process for transforming the outcome of a Javascript function into a webpage containing solely a JSON string?

I have a specific requirement where I need to fetch a URL and ensure that the only content displayed on the page is a JSON string. For instance, let's say I created a basic function called getDayOfWeek() to determine the current day of the week. The ...

Submitting data using JavaScript's POST method

I am facing a challenge with posting Array data to an HTTP connector. My data is structured as follows: var data = [{ key:'myKey', keyName:'myKeyName', value:'value', valueName:'valueName' }, { ...

Matching CSS attribute values with another attribute

Can CSS be used to target elements based on the value of another attribute? For instance: <div data-attr1="abc" data-attr2="def"></div> <div data-attr1="abc" data-attr2="abc"></div> I am looking for something like this (although i ...

Utilizing Jquery for a Date Picker on iPhone Devices

Currently, I am facing some issues with loading the date picker using mobilscroll jQuery on my iPhone. I have added the necessary mobiscroll files to Xcode and have called index.html in a web view. However, I am encountering a problem where nothing is be ...

What is the best way to interact with both the child and parent controllers within a directive?

We currently have two directives known as parent and child. Both of these directives come with controllers that house specific functionalities. In the case of the child directive, there are a couple of ways to access controllers: We can access the parent ...

Conflict arises between Angular $scope and the file input type

I have been attempting to convert a file into a byte array using AngularJS. The conversion process is successful and I am able to add the byte code and filename to an array ($scope.FileAttachments). However, there seems to be an issue with ng-repeat not wo ...

Link a timestamp to a datetime-local input using ng-model

My challenge is to display an <input type="datetime-local> field using the ng-model attribute to represent a timestamp: <input type="datetime-local" ng-model="object.value"> This is being achieved with: $scope.object.value = 1433109600000; ...

jQuery's capability to select multiple elements simultaneously appears to be malfunctioning

I am dynamically creating div elements with unique ids and adding span elements with specific CSS properties. $(".main").append("<div class=largeBox id=" + counter + "</div>"); $(".largeBox").append("<span class=mainTitle></span>"); ...

Getting a user's group name from Azure Active Directory in an Angular application - a step-by-step guide

I have connected to Azure directory using ng2-adal (https://github.com/mazhisai/ng2-adal-QuickStart) and successfully obtained a group id in the format: "groups":["4ba2649e-20d2-40f4-a406-2ed897686403","43e19f05-c077-4716-b001-0ffb0d75fff8"]. Is there a w ...

Ways to update a specific div upon clicking an image

Is there a way to refresh a div using an image click? I have an image with the id 'sellhide' and another div with the id 'sellChart'. Below is the code: <div class="col-xs-12 col-lg-6 col-sm-6 col-md-6 index_table_three" id="sellCha ...

Is there a foolproof way to determine when a dialogue box pops up on

I'm currently building an electron app using vue and Vuetify. I am able to create a modal using dialog, but I want to be able to modify certain elements within the dialog after it is displayed. When using $refs, I cannot find the element before the d ...

Distinctive color transformations to emphasize varying conditions

Is it possible to change the color of a highlighted area on a map based on different conditions? Take a look at my code snippet: if(partyname = "Democrat") { var data = $('#MT').data('maphilight') || {fillColor:'ff0000&apos ...

Transferring an organized array to processing

My goal is to transfer an array of integers from a php file called load.php to a JS script, which will then forward it to a Processing file written in JavaScript. In load.php, I define the array and send it using JSON (the array contains a minimum of 40 i ...