1

I have this JSfiddle and i need to slide in, when clicking on a div, and not when page is loaded. Simultaneously it should be possible to close by clicking anywhere outside the slide-in box.

$( document ).ready(function() {
    $(function(){
        $(".slide-in").addClass("active");
        console.log($(".slide-in"));   
    });
});

I think the solution could be some kind of toggle system, but i can't figure out how to?

Thank you!

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252

4 Answers4

1

Try this.

var someDiv = document.getElementById('yourDiv');

someDiv.style.cursor = 'pointer';
someDiv.onclick = function() {
  //do something  
}

how to make div click-able?

Community
  • 1
  • 1
Fennek
  • 197
  • 1
  • 11
1

I think this should do the trick.

Edit:

$( document ).ready(function() {
  $(".button").on("click",function(){
    if($(".slide-in").hasClass("active")){
      $(".slide-in").removeClass("active");
    }else{
        $(".slide-in").addClass("active");
    }  
  });
});
dvenkatsagar
  • 936
  • 7
  • 22
  • This closes only if the .slide-in is clicked, not "anywhere outside the slide-in box" – Petr Hejda Jan 24 '16 at 23:00
  • It sort of works, but when i need to close it, i would like the button to trigger it back. At the moment you need to click the slide-in itself. How can I change this - thank you! – Mikkel Lehrmann Jan 24 '16 at 23:03
  • @MikkelLehrmann Well I edited the answer, Depending on you needs, you can use this as well... – dvenkatsagar Jan 24 '16 at 23:27
1

Opens the slider on click of .button. Closes it on click anywhere outside the slider (including the button)

var isOpened = false;
$(document).click(function(e) {
  if(isOpened && e.target.className=='slide-in') {
    $(".slide-in").removeClass("active");
    isOpened = false;
  } else if(!isOpened && e.target.className=='button'){
    $(".slide-in").addClass("active");
    isOpened = true;
  }
});

Better is to use IDs. So your code would be:

<div id="slide-in"></div>
<div id="button"></div>

and the javascript:

var isOpened = false;
$(document).click(function(e) {
  if(isOpened && e.target.id!='slide-in') {
    $("#slide-in").removeClass("active");
    isOpened = false;
  } else if(!isOpened && e.target.id=='button'){
    $("#slide-in").addClass("active");
    isOpened = true;
  }
});

You'll also need to change the CSS from classes to IDs

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
1

https://jsfiddle.net/zer00ne/jne1rasb/

$(document).ready(function() {
  $('.button').on('click dblclick', function(e) {

    $('.slide-in').toggleClass('active');
    e.stopPropagation();

  });
  $(document).on('click', function() {
    $(".slide-in").removeClass("active");
  });
});
zer00ne
  • 41,936
  • 6
  • 41
  • 68