Expand the width of the div by a specified amount with each click

Greetings Everyone!

I've scoured the internet high and low in search of a solution, but I have yet to come across exactly what I need.

The Issue at Hand

My goal is to expand the width of my Div every time I click on my Button. All I have is my DIV element and the value by which I want to increase it. I just need guidance on how to accomplish this task.

Here's the Code snippet: https://codepen.io/keanubarnardd/pen/XyXQZE?editors=1010

What I've Attempted and Discovered

In conducting my own research, all I could find was:

  • Using this approach:
    document.getElementById('example').style.width="400px";
    while this does alter the width - it doesn't align with my objective as I wish to increment it by a specific amount for each click.

Answer №1

Utilize

var widthElem= document.getElementById('rough-in-bar').offsetWidth;

to retrieve the current width and set a new width

document.getElementById('rough-in-bar').style.width=widthElem + 100 + 'px'

For preventing overflow from the grey section, you can implement:

   if(widthElem<document.getElementById('rough-in-progress').offsetWidth-10)
     document.getElementById('rough-in-bar').style.width=widthElem + 100 + 'px'

    //Data
    var roughInTotal = 0;

    //Text
    var roughInText= document.getElementById("rough-in-total");

    //UI Objects
    var roughInButton = document.getElementById("rough-btn");

    var roughInBar = document.getElementById("rough-in-bar");

    roughInButton.addEventListener("click",function(){
        addHour(1, roughInText);
    });
    //Setting everything on our website
    roughInText.textContent =  roughInTotal + " hours";
    

     function addHour(addAmount, textToChange) {
        //Add the amount of hours worked...
        roughInTotal += addAmount;
        //Update the display of our text
        textToChange.textContent = roughInTotal + " hours worked";
        //Debug the amount of hours we have

        var widthElem= document.getElementById('rough-in-bar').offsetWidth;
       if(widthElem<document.getElementById('rough-in-progress').offsetWidth-20)
       document.getElementById('rough-in-bar').style.width=widthElem + 100 + 'px'
    }
  <style>
    body{
        font-family: 'Roboto Condensed', sans-serif;
        margin: 0;
    }

    h1 {
        text-align: center;
        font-weight: 100;
        font-size: 270%;
        color:white;
        margin: auto;
        height: 50px;
        padding-top:10px;
    }

    div { 
        margin: 5% 5%;
        background-color: rgb(250, 233, 249);
        padding:20px;
        box-shadow: 0px 4px 4px rgba(44, 62, 80 ,0.15);
    }

    h4{
        text-align: center;
    }

    h2{
        font-weight: bold;
        text-align: center;
        text-transform: uppercase;
        padding: 0px;
        margin:auto;
    }
    .item p{
        width: 100%;
        height: 10%;
    }

    #rough-in-total{
        background-color: rgb(197, 197, 197, 0.6);
        padding: 5px;
        box-shadow: 0px 4px 4px rgba(2, 2 , 2, 0.10);
    }

    p{
        text-align: center;
        font-size: 20px;
    }

    header p {
        margin-top: 0;
        color: white;
        font-family: 'Roboto Condensed', sans-serif;
        font-size: 0.8em;
        font-weight: 100;
        text-transform: uppercase;
    }
    button{
        text-decoration: none;
        font-size: 100%;
        padding: .5em 1em;
        color: rgba(0, 0, 0, 0.8);
        border: transparent;
        background-color: rgb(201, 199, 199);
        border-radius: 2px;
        margin-left: 45%;
        box-shadow: 0px 4px 4px rgba(2, 2 , 2, 0.10);
    }

    button:hover{
        background-color: rgb(90, 90, 90);
        color: white;
    } 
    header{
        background-color: rgb(109, 109, 146);
        height: 100px;
    }

    #rough-in-progress{
        width:100%;
        margin: auto;
        margin-bottom: 20px;
        height: 30px;
        padding: 0;
        background-color: gray;

    }

    #rough-in-bar{
        width: 1%;
        height: 30px;
        background-color: rgb(255, 152, 241);
        margin: auto;
        padding: 0;
        box-shadow: none;
    }
    </style>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300" rel="stylesheet">
    <title>Breakwell Electrical</title>
</head>
<body>
    <header>
            <h1> Welcome Keanu Barnard</h1>
            <p>This will include how many hours you have worked at each job</p>
    </header>

    <section>
        <div class ="item">
            <h2><span>Rough In's</span></h2>
            <p>This will be an account for how many hours you have spent working at rough ins with break well. Including marking out 
                   ,roughing in cable etc..
            </p>
            <!--Insert our Horizontal Graph Here that will increase when we add hours to it for now we just use number-->
            <p id ="rough-in-total"> 123 hours</p>
            <div id ="rough-in-progress">
                <div id="rough-in-bar">

                </div>
            </div>
            <button id = "rough-btn">Add hour</button>
        </div>
    </section>

Answer №2

<style> 
  .bar{
  border:1px solid #000;
  }
</style>

<script>
function func(){
var currentWidth = document.getElementById('box').style.width;
currentWidth = currentWidth.replace('px','');
document.getElementById('box').style.width = (parseInt(currentWidth) + 100).toString() + "px";
document.getElementById('box2').style.width = (parseInt(currentWidth) + 100).toString() + "px";
}
</script>

type 1

<div class='bar'>
<div id="box" style="width:100px;height:50px;background-color:red;">

</div>
</div>

<br><br>

Type 2

<div class='bar'>
<div id="box2" style="width:100px;height:50px;background-color:red;position:relative;left:50%;transform:translateX(-50%)">

</div>
</div>

<br><br>

<button onclick="func()">Check this...</button>

Answer №3

Here is a sample code snippet for you to use:

function updateButtonWidth() {
  const button = document.getElementById("myButton");
  const currentWidth = button.offsetWidth;
  button.style.width = currentWidth + 300 +"px";
}
<!DOCTYPE html>
<html>
  <body>
    <button type="button" id="myButton" onclick="updateButtonWidth()">
      Change the width of this button
    </button>
  </body>
</html>

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

Looking to obtain an audio file from a URL in Node.js?

Is it possible to save an audio file from a URL to a local directory using Node.js? Below is the code I attempted: var http = require('http'); var fs = require('fs'); var dest = 'C./test'; var url= 'http://static1.grsite ...

The setInterval() function is not functioning properly when used with PHP's file_get_contents

Currently, I'm encountering an issue while attempting to use the function get_file_contents() within a setInterval(). The objective is to continuously update some text that displays the contents of a file. Below is the code snippet: <script src="h ...

Attempting to allocate an identifier to a for loop function

My goal is to assign an id to my dynamic information. The issue arises when I attempt to add the id="[index] in this line: var webaddress = '<img id= "[index]" src="http://pokeapi.co/media/img/[index].png">'; Removing id="[index] allows ...

Enhancing the functionality of an existing framework through the integration of a

My coding style involves a lot of ASP.NET MVC and jQuery, particularly with ajax calls that return json. Lately, I've been tinkering with organizing my code structure by creating an object within the global object which contains success and fail callb ...

Navigating through error messages in NextJs 14 can be tricky, especially when faced with the dreaded "ReferenceError: document not defined" or "prerendering error". It's vital to pinpoint exactly which page

When attempting to run the build on my Next.js application, I encountered an error message that is not very informative given the number of files/pages in my project. How can I pinpoint the exact location of this error and determine the root cause? The pro ...

Ways to trigger the display of an image upon hovering over a button without using inheritance

<div class="a"> <img class="img_c" id="img_id" src="~~"> <div class="b"> <div class="c"> <ul class="d" id="e"> <li ~~~ > </ul> </div> </div> </div> Is there a way to display the ...

What is the best way to determine if a checkbox has been selected in ExtJS?

I have a panel with a checkbox inside it. I am trying to figure out how to check if the checkbox is selected or not using an external function. Can someone please assist me with this? this.currentManagerPanel = new Ext.Panel({ border: false, wid ...

Angular array mapping techniques

My JSON Object $scope.selectedItems ={ "RECORDS": [ { "Id": 23040035705987, "arriveddate": "2015/04/24", "expirationDate": null, "replacedDate": null, "processDate": "2015/04/24" ...

Tips for displaying my libraries' function arguments while hovering in VSCode

As the creator of a JavaScript library, I am intrigued by how some libraries display function parameters and definitions when hovering over them in VSCode. Despite my efforts to add jsdoc style comments around the class definitions, I have not been able to ...

Having trouble incorporating a variable into the Discord Client object in Typescript

As a newcomer to Typescript, I am working on creating a Discord bot using Typescript. I am trying to add a variable called "commands" to the Client object. In JavaScript, you can achieve this using the following code: Javascript const { Client } = require ...

The masonry reorganization is behaving strangely

I've recently started using masonry for the first time and you can check it out here: Although I have managed to set it up, I am facing some issues with its positioning of boxes when dragging items in. For example, instead of placing a medium-sized ...

What is the best way to include a permanent placeholder within an input field?

I'm trying to insert a font icon inside an input field using the following method: <input type="text" name="your name" placeholder="&#xe00b; YOUR NAME" style="font-family:Flaticon" class="restrict"> Currently, the font icon &#xe00b; is ...

I'm feeling uncertain about the installation process of Nodejs

I recently updated to the newest version of node, 20.10.0, so I can begin working with React. What should I do with the previous version? Is it safe to delete it or is it better to keep it? If I decide to remove it, could that impact any existing files t ...

Experience the full functionality of Google Maps API without the need for jQuery or PHP with PanTo

I'm not a developer and I find myself stuck in the panTo() function. All I want is to execute this function with an if-else statement without having to reload the Google Map or using jQuery. <body> <div id="map"></div> <d ...

Retrieve the AngularJS scope object by using an alternate scope object as the identifier

As I loop through an array of person objects using ng-repeat, imagine the array looks something like this: [{ "display_name": "John Smith", "status": "part-time", "bio": "I am a person. I do people stuff.", }, { "display_name": "Jane Doe", "stat ...

An issue has been identified where a single image is not displaying properly on Android devices, as well as IE7 and

Hey there! I recently created a Wordpress site and it seems that the Art Below logo isn't appearing in IE7, IE8, and Android for some reason. Would anyone be willing to help troubleshoot this issue? If you have fresh eyes, please take a look at the f ...

Tips for dynamically adding an external SVG animation to your website:

When trying to insert an animated SVG using jQuery or plain JavaScript, they appear static in Chrome and Edge, but display correctly in Firefox: $(".loader").prepend("<svg><use xlink:href='/images/icons.svg#loading-ring'></use> ...

Unusual display of footer controlled by CSS in certain template pages

I recently made changes to the footer on a template-based website. I noticed that, for some unknown reason, the footer is not appearing at the bottom of the page as it should be. I wonder if the footer functionality is faulty altogether and if I only got ...

How to Insert a Background Image into Advanced Custom Fields (ACF) using CSS

Hey there, I'm facing a bit of a challenge with this particular section. In the past, I've only included ACF PHP within HTML when the background image was directly in the HTML code. Now, however, I have two shapes specified in my CSS using pseudo ...

Converting Python conditional statements to Javascript control flow

How can I achieve this task using JavaScript? I want it to output 'Found' when it finds the word words in the big_list big_list = ['this', 'is', 'a', 'long', 'list', 'of' 'words&ap ...