1

This is an example of a scenario I have got:

<div id="portfolio">
  <a class="show-project" href="#">
    <!-- some content here -->
  </a>
  <div class="scrollable">
    <!-- full height container with scroll -->
  </div>
</div>

When link is clicked, additional class is added to "scrollable move-left". I would like to detect when it is added and replace css "overflow-y: auto;" with "overflow-y: hidden;"

I am trying to achieve this with:

<script>
  $(document).ready(function () {
    $("#portfolio .show-project").click(function(){
      if ($("#portfolio .scrollable").hasClass("move-left")) {
        $("#portfolio").css("overflow-y", "hidden");
      } else {
        $("#portfolio").css("overflow-y", "auto");
      }
    });
  });
</script>

Could you advice me how to fix this please? Very appreciated!

1
  • For detect if there are changes with any classes, attributes, properties etc. the best plugin is github.com/RickStrahl/jquery-watch. I use it in many my projects. Works perfect and easy to use Commented Oct 24, 2015 at 16:37

1 Answer 1

2

You can use jQuery toggleClass and hasClass in order to toggle the class on the element and change the overflow-y attribute accordingly.

Ref:

Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.

Code:

$(document).ready(function () {
    $("#portfolio .show-project").click(function () {
        $("#portfolio .scrollable").toggleClass('move-left');
        var overflow;
        ($("#portfolio .scrollable").hasClass("move-left")) ? overflow = 'hidden' : overflow = 'auto';
        $("#portfolio").css("overflow-y", overflow);
    });
});

Demo: http://jsfiddle.net/IrvinDominin/n0d5jxe8/

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Irvin for you example - it works. It works with html example I posted. Would you be able to advice on how to make it work in a next example please. Code: jsfiddle.net/bmkjvz5v/2 At the moment all of the "scrollable" containers are getting "move-left" class. Is there a way to detect if "move-left" was added or removed and depending on this "#portfolio" will have overflow-y: hidden or auto? There is already JavaScript in place that is adding / removing "move-left" Maybe .click is not needed for this to work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.