Adjusting the Height of a Div Using a Single Button

Seeking help to make a div expand and then shrink with one button click. I've tried various methods but the div won't change size. Can someone guide me on why this is happening?

Here is the code, CSS, and HTML for my latest attempt:

$("dasButton").toggle(function(){
$("#div1").height($("#div1").height()+200);
},function(){
$("#div1").height($("#div1").height()-200);

});

});

CSS

#div1{
background-color:#8888ff;
display:block;
height:0px;
overflow:hidden;
    border: 1px solid #000;
 }

HTML

<input type="submit" class="toggle_div" id="dasButton" value="Enlarge/Shrink div"/><br>
<div id="div1">
display:block;
height:0px;
overflow:hidden;
    border: 1px solid #000;
}

http://jsfiddle.net/sen3t6vk/3/

Answer №1

i have modified the code for you!

Using jQuery:

$("#dasButton").click(function(){
    var inputValue=$("#dasButton").attr('value');

    if(inputValue=="Expand")
    {
        $("#div1").animate({height:"200px"});
        $("#dasButton").attr('value','Reduce');
    }
    else if(inputValue=="Reduce")
    {
        $("#div1").animate({height:"0px"});
        $("#dasButton").attr('value','Expand');
    }
});

Your HTML:

<input type="submit" class="toggle_div" id="dasButton" value="Expand"/><br>
<div id="div1">

Check it out live on JSFiddle

Answer №2

In jQuery 1.9, the .toggle() event was removed from use. However, if you happen to have an older version of jQuery installed and correct any errors that may arise, it should still function properly:

Check out this jsFiddle demo

$("#myBtn").toggle(function () {
    $("#box1").height($("#box1").height() + 150);
}, function () {
    $("#box1").height($("#box1").height() - 150);
});

Answer №3

The toggle() method doesn't support writing a function within it; it only accepts a speed parameter (integer).

One alternative approach could be like the following example:

$("#dasButton").click(function (e) {
    var wdth = $("#div1").width();
    if (wdth > 0) {
        $("#div1").width(0);
        $("#div1").height(0);
    }
    else {
        $("#div1").width(200);
        $("#div1").height(200);
    }
});

Answer №4

Concise and accurate:

$("button").on("click", function () {
    var element = $("#element1");
    element.width(element.width()==150 ? 0 : 150);
})

Check it out here

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

Several treeviews for selecting data

I need some help with a specific assignment. The back end code is all set, but I'm struggling with the UI component. The task requires two tree views, one on the left and one on the right. The left tree view will contain states with multiple children, ...

Issue encountered: Compilation error occurred following the update from Angular 11 to Angular 15, stemming from the module build failure within the sass-loader directory

I recently attempted to update angular from version 11 to 15, but encountered an error as shown in the screenshot below ./src/assets/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: expected "(". ...

Is it possible to create a subclass component to customize the event handler?

Looking to modify the behavior of a complex React component (specifically, Combobox from react-widgets)? I want to customize the onKeyDown event so that when the enter key is pressed, I can handle it myself without affecting the Combobox's default fun ...

What is the best way to implement an 'onKeyPress' event listener for a <canvas> element in a React application?

I've been working with React for a while now and I understand how its event system functions. However, I've run into an issue where the onKeyPress event doesn't seem to be triggering on a <canvas> element. Surprisingly, it's not w ...

Guide to dynamically generating Angular watchers within a loop

I'm looking to dynamically create angular watches on one or more model attributes. I attempted the following approach: var fields = ['foo', 'bar']; for (var i=0, n=fields.length; i<n; i++) { $scope.$watch('vm.model.&ap ...

Sorting through an array of dates in milliseconds, extracting objects with subcategories, and dynamically displaying them on the calendar based on the specific date

So I am currently working with a JSON object containing an array of objects structured like this: [ { "id": 0, "name": "Sophia Mason", "availability": [ { "date": 1522216800000, "times": ["9:00 am", "2:3 ...

What is the best way to link JSON array information to the HTML using MVC?

I'm currently working with MVC5 and I am trying to populate a div element with data using the .html(data) method. .done(function (data) { var result = $.parseJSON(data); $("#mydata").html(result); }); <div id="mydata"></div> Th ...

Using maxCDN to deliver static files within a Node application

Our current project is built using keystone and nunjucks, with all paths to static files following the format /stc/img/someimage.jpg. I am looking for a way to serve these files through middleware in our node server from maxCDN. Is there a solution that ...

The vertical-align property in CSS seems to be malfunctioning

Hi there, I'm struggling with the CSS code below: .parent { position : 'absolute'; top : '50px'; left : '50px'; width : '400px'; height : '160px'; padding : '10px'; ...

Refreshing a model using angular.js

I am attempting to reset values in the following way: $scope.initial = [ { data1: 10, data2: 20 } ]; $scope.datas= $scope.initial; $scope.reset = function(){ $scope.datas = $scope.initial; } However, this code ...

Create a fresh CSS class using the Chrome developer tool

Can a brand new CSS class be inserted in Chrome dev tools in this way? .myclass { background-color: yellow; } ...

Attempting to locate the element's position using Selenium in Python

quem_esta_sacando = driver.find_elements_by_xpath("//div[@class='gameinfo-container tennis-container']/div[@class='team-names']/div[@class='team-name']") this is how I located the correct class, but now I want to ...

Every now and then, Ajax gets stuck

My website uses this code to request new chat messages and display them, but I've been running into an issue where it freezes at times and stops fetching new messages. (function worker() { $.ajax({ url: '/client_message.php?get_messa ...

Tips for showcasing the chosen menu item in the toggle button of the Bootstrap framework

I have created a collapsible menu that is hidden when the browser is resized and should be displayed when the button is toggled. Currently, I am using glyphicon-humberger in the toggle button. However, I would like to show the selected menu in the button ...

The search bar fails to display all pertinent results when only a single letter is inputted

How can I create a search functionality that displays array object names based on the number of letters entered? When I input one letter, only one result shows up on the HTML page, even though the console.log displays several results. The desired output is ...

What is the best way to darken the background when an alert is displayed and disable the dimming effect when the alert is closed?

Here's the JavaScript snippet I'm using: reset.addEventListener("click", function(){ document.querySelector("#body").classList.add("darkenPage"); myReset(); alert("Reset Successful!!"); document.querySelector("#body").classList.re ...

Pass the selected ID from a Vue.js select component to an Axios post request and then render another select

Forgive me if this is a silly question, as I am new to Vue.js and JavaScript. I'm having trouble getting the id from one select element and using it in another API to display models in the next select element. The listings are working fine when I hard ...

The raycaster's intersectObjects function consistently results in an empty array

I've been working on implementing a raycaster to find intersections, but no matter what I do, it always gives back an empty array. Here's how I add objects to my objects array: var obstructionGeom = new THREE.BoxGeometry(6,5,0.5); var obstructi ...

Guide on populating a Kendo grid using a specific property from the server's JSON response, rather than the entire object

Here is the setup for my custom kendo grid: $("#grid").kendoGrid({ dataSource: { transport: { url: "customers", type: "GET", ...

How can I show the content of a variable in Next.js without displaying any HTML tags?

For instance, I have the description variable set up like this in NextJS: description={storeDetail?.translation?.description} When outputting the description, it shows me <p>Tenis</p>. However, I would prefer to display just "Tenis" without th ...