Xander
Xander

Reputation: 397

Javascript change css when any other element is clicked

Right now I have a menu fixed to the bottom of the screen that is 35px in height, and when clicked it does this:

Javascript Code

    function slideChat() {
    div = document.getElementById('chat-slide');
    div.style.height = "100px";
    div.style.transition = "height .4s ease";
    }

HTML Code

 <div id="chat-slide" class="mobilechaticonON">
      <button onclick="javascript:slideChat();" class="mobilechat"><span></span></button>
      <br>
      <button class="smschat"><a href="bing.com"><span></span></a></button>
      <br>
      <button class="webchat"><a href="google.com"><span></span></a></button>
    </div>

CSS

.mobilechaticonON {
  display: block;
  height: 35px;
  position: fixed;
  bottom: 0;
  left: 21%;
  width: auto;
  padding: 5px 15px;
  background: #16a085;
  border-radius: 4px 4px 0px 0px;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.6);
  z-index: 999;
  transition: height .4s ease;
 }
 .smschat span:before {
     content:"Chat through text message";
 }
 .webchat span:before {
     content:"Chat using web chat";
 }
 .mobilechat span:before {
     content:"Live Sales Chat - Online!";
 }
 .mobilechaticonON button {
     border: 0;
     background: transparent;
     height: 35px;
 }
 .mobilechaticonON button span:before {
     font-family: Arial;
     font-size: 1.2em;
     color: #fff;
 }

I'm trying to figure out a way to when the user clicks on something else outside of this div, the div goes back down to 35px instead of 100px. Not having any luck so far.

Here is a fiddle but I'm not sure why the initial slide function doesn't even work over there. Works fine on my normal page. O.o

Upvotes: 1

Views: 1893

Answers (1)

adeneo
adeneo

Reputation: 318182

Target the document, and if the click originated from any element outside chat-slide, change the height back

$(document).on('click', function(e) {
    console.log('clicking anywhere works !');
    if ( ! $(e.target).closest('#chat-slide').length ) {
        $('#chat-slide').css('height', '35px');
    }
});

And if you're using jQuery (you tagged it with jQuery) use a proper event handler

$('.mobilechat').on('click', function() {
    console.log('clicking the button works !');
    $('#chat-slide').css({
        height: '100px',
        transition : 'height .4s ease' 
    });
});

and at the same time change

<button onclick="javascript:slideChat();" class="mobilechat">

to just

<button class="mobilechat">

Upvotes: 3

Related Questions