I am trying to master JS and jQuery, but I can’t resolve this task.
Task : 1 click on button, we are getting black background on website, 2 – click, we are removing all changes and back to default what was before.
It getting black background, but second click does not work.
Thank you for help
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<button type="button" id="button">Button for test</button>
script type="text/javascript">
$(document).ready(function(){
function on_contrast(){
$('body').css('background', 'black');
function off_contrast(){
$('body').css('background', 'black').off();
};
$('#button').click(on_contrast);
$('#button').click(off_contrast);
});
</script>
I tried many times and different options, but looks like I do not understand logic in some places.
3
Answers
I added a variable isBlack to keep track of the current state of the background color. It toggles between true and false each time the button is clicked.
The if-else block checks the value of isBlack. If it’s true, the background is set back to the default (empty string ” resets it to whatever the default was before). If it’s false, the background is set to black.
After setting the background color, the code toggles the value of isBlack using isBlack = !isBlack;
If you use CSS for styling and set the class name of the body, you can start to style any element on the page according to the state.
}
.off()
method is well documented here and it’s a counter method to the.on()
which you’ll learn how to use in this example.click()
method, use rather the preferred.on()
method to assign event handlers like$("#button").on("click", toggle_contrast);
$("#button").off("click", toggle_contrast);
(will stop listening (unsubscribe) to click events for that specific callback function).toggleClass()
method to toggle a specific modifier CSS class from a target element.dark{}
styles and toggle it using JavaScriptAnd yes, jQuery is nowadays not that much necessary for those simple tasks. You can rewrite the above in pure JavaScript without the overhead of an entire JS library (like jQuery — or any other)