I am trying to implement a dynamic scrolling feature in my post scenario. The goal is to automatically add a vertical scroll when the number of dynamic inputs reaches a certain threshold. Specifically, if there are more than 5 dynamic inputs created, a vertical scroll should be added to prevent the div from extending beyond the body height. Additionally, the scroll should be removed when the user removes inputs and the total falls below 5. However, my code doesn't seem to be working as expected.
$(document).ready(function() {
var max_fields = 100; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
console.log('check length', wrapper.length);
var add_scroll = wrapper.css("overflow", "scroll");
var remove_scroll = wrapper.css("overflow", "hidden");
function checkForScroll() {
if (wrapper.length > 5) {
add_scroll;
}
if (wrapper.length < 5) {
remove_scroll;
}
}
checkForScroll();
var x = 1; //initial text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
checkForScroll()
console.log('check length', wrapper.length);
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
checkForScroll()
console.log('check length', wrapper.length);
})
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="./js/test.js"></script>
</body>
</html>