html - How do I set a div width equal to a Javascript variable? - Stack Overflow

I am trying to make a div expand as the user presses a button over and over again.<script>heartCl

I am trying to make a div expand as the user presses a button over and over again.

    <script>
            heartClicks=10;
            function love(){
                heartClicks++;
            }
      </script>

How can I set the width of the div equal to heartClicks?

        <div id="luv"></div>

I am trying to make a div expand as the user presses a button over and over again.

    <script>
            heartClicks=10;
            function love(){
                heartClicks++;
            }
      </script>

How can I set the width of the div equal to heartClicks?

        <div id="luv"></div>
Share Improve this question edited Sep 26, 2013 at 23:51 Thought Space Designs 4291 gold badge5 silver badges17 bronze badges asked Sep 26, 2013 at 23:25 user2821453user2821453 111 silver badge2 bronze badges 3
  • 2 you mean how to set the width of the div depending on the heartClicks variable? – Krimson Commented Sep 26, 2013 at 23:31
  • Are you asking how to set the div width to the value of a JavaScript variable, or are you asking how to set the JavaScript variable to the value of the div's width? Your title asks for one, but the question itself asks for the other. – doppelgreener Commented Sep 26, 2013 at 23:33
  • if you want to make the div expand based on how many times the user clicks, you will need to dynamically change the width of the div, not set the heartClicks equal to the width of the div. I made this assumption in my answer. I assumed it was a typo but correct me if I'm wrong. – aug Commented Sep 26, 2013 at 23:36
Add a ment  | 

4 Answers 4

Reset to default 3
document.getElementById('luv').style.width = heartClicks + "px";
document.getElementById("luv").style.width = heartClicks + "px";

Something to keep in mind is you're going to need to reset/reapply the style everytime they click so you might want to stick this in your button click function.

var heartClicksElement = document.querySelector("#luv");
heartClicks = heartClicksElement.style.width;

@aug's answer is great for standard javascript (make sure you have an event handler). If you want to use jQuery (or if anyone else browsing this question wants to use jQuery) try the following:

var heartClicks=10;

$(function(){
    $('#expand').on("click",function(){
        heartClicks++;
        $('#luv').css({'width':heartClicks});
    });
});

Try it out with this working fiddle.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744707651a4589149.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信