Click on the hamburger to trigger the CSS transition

The objective of my project is to create an interactive hamburger icon that transforms into a cross when clicked, and reverts back to its original state on a second click.

While I have successfully implemented a transition on hover and click through research, I am struggling to achieve the desired outcome. Can anyone offer some guidance or tips?

Update

As requested, you can find a demo here - here Below are snippets of the CSS code related to the transition effect. I attempted using toggle from JQuery to simulate a continuous click but faced challenges. Is this approach advisable for accomplishing my goal?

CSS

.burge:active span {
    background-color: rgba(0,0,0,0.0);
    transition-delay: .2s;
}
.burger:active span:before {
    background-color:#7dcc3d;
    transition-property: margin, transform;
    transition-duration: .3s;
    transition-delay: .3s, 0;
}
.burger:active span:before {
    margin-top: 0;
    transform: rotate(45deg);
    transition-delay: 0, .3s;
}
.burger:active span:after {
    background-color:#7dcc3d;
    transition-property: margin, transform;
    transition-duration: .3s;
    transition-delay: .3s, 0;
}
.burger:active span:after {
    margin-top: 0;
    transform: rotate(-45deg);
    transition-delay: 0, .3s;
}

Answer №1

If you're looking to achieve this functionality without relying on JavaScript, one alternative is to utilize a checkbox element.

Below is a simple example demonstrating how you can implement a toggle button for open/close states:

.burger + label {
  position: relative;
  
}
.burger + label:after {
  content: '☰'
}
.burger:checked + label:after {
  content: 'X'
}
<input type="checkbox" id="checkbox1" class="burger"><label for="checkbox1"></label>

Answer №2

When it comes to detecting a click event, CSS falls short in that aspect. It is crucial to note this detail. The solution is to replace all instances of :active with a class (such as .active) and then use jQuery to trigger a toggleClass function in JavaScript:

.burger.active span {
    background-color: rgba(0,0,0,0.0);
    transition-delay: .2s;
}
.burger.active span:before {
    background-color:#7dcc3d;
    transition-property: margin, transform;
    transition-duration: .3s;
    transition-delay: .3s, 0;
}
.burger.active span:before {
    margin-top: 0;
    transform: rotate(45deg);
    transition-delay: 0, .3s;
}
.burger.active span:after {
    background-color:#7dcc3d;
    transition-property: margin, transform;
    transition-duration: .3s;
    transition-delay: .3s, 0;
}
.burger.active span:after {
    margin-top: 0;
    transform: rotate(-45deg);
    transition-delay: 0, .3s;
}

For the jQuery implementation:

$(".burger").click(function(event){ $(this).toggleClass("active"); });

Alternatively, here is a pure JavaScript approach:

var burgers = document.querySelectAll(".burger");
for(var i = 0; i < burgers.length; i++){
    burgers.item(i).addEventListener("click", function(){
        if(burger.className.indexOf("active").length){
            burger.className = burger.className.replace("active", "");
        } else {
            burger.className += " active";
        }
    }, false)
}

Please be aware that the quick and basic implementation of toggleClass may not cover all edge cases. It is recommended to use the jQuery version for smoother functionality (the pure JS version might cause issues when dealing with classes like 'js-active', potentially breaking the code).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you efficiently cache a component fetching data from an API periodically in React?

I have a situation where I need to continuously fetch data from an API at intervals because of API limitations. However, I only want to update the state of my component if the API response is different from the previous one. This component serves as the m ...

What could be causing the abrupt termination of the ajax request?

Currently, I am making an ajax request to the server $.ajax({ type: "POST", data: checkin_push, url: api_url + 'file.php?token=' + last_token + '&date=' + dated, dataType: "json", timeout: 100000, // 100 seconds ...

CSS behaving strangely with the height property

I've run into a specific issue with a div element that contains multiple buttons. I am trying to adjust the height and position of one button so that it takes up space above the other buttons, but every time I make changes to its height and position, ...

Trouble retrieving data using component props

I am currently facing an issue with displaying data from the API in a component. The request is being made from the parent page, but the loop to display the data is within the child component. Unfortunately, the data is not showing up on the parent page as ...

Accessing files for MongoDB cluster

My goal is to retrieve all the documents from a MongoDB cluster. Even though I have followed code examples from various online sources, I am encountering a minor issue. const MongoClient = require('mongodb'); const uri = "mongodb+srv://<user& ...

Is there a way to properly align unordered lists (such as a navigation menu) within a div with a width set at

UPDATE: I found a creative solution to my issue. By adding margin-left and margin-right set to auto, along with fixing the width of the nav menu to 1002px and setting its positioning to relative, I was able to achieve the desired effect. Additionally, I cr ...

A callback function within a Node.js transform stream

Here is a demonstration of transform stream in Node.js: Sample code : const { Transform } = require('stream'); const transtream = new Transform({ transform(chunk, encoding, callback){ this.push(chunk.toString().toUpperCase()); ...

Issue with Yup and Formik not validating checkboxes as expected

I'm struggling to figure out why the validation isn't functioning as expected: export default function Check() { const label = { inputProps: { "aria-label": "termsOfService" } }; const formSchema = yup.object().shape({ ...

FireFox supports JavaScript functionality, whereas Chrome and IE do not execute JavaScript code

Here is a snippet of my code where I am creating a div with a dropdown box on my webpage. I would like to trigger an onClick event when an element in the select box is selected: $("div.projectTeamTools").html('Organize by Project Teams: <select id ...

Attempting to dynamically link my "ng-true-value" in AngularJS

Working with values retrieved from a database, my goal is to include a checkbox, load the description, and provide 2 text boxes – one editable and the other read-only. Both text boxes initially display values from the database. When the checkbox is chec ...

How to create list item bullets with a star icon using reactstrap/react?

As a machine learning professional looking to enhance my frontend skills, I am curious about how to create list item bullets using a custom star bullet image. Could anyone please share a complete HTML/CSS example with me? Thank you in advance! ...

Flowing Waterways and Transmission Control Protocol

I have a unique piece of code that I recently discovered. After running it, I can connect to it using a Telnet client. const network = require('networking'); //creating the server const server = network.createServer(function (connection) { ...

Illuminate XHR 500 (Server Side Issue)

I'm currently troubleshooting an issue with this AJAX script, but I'm unable to identify the specific problem. The Chrome developer tools are indicating a "500 (Internal Server Error), doWork @ (index):16 , onclick @ (index):28" Is there anyone ...

Tips for creating a clickable popover within a window that remains open but can be closed with an outside click

Is there a way to ensure that my popover window remains clickable inside its own area without closing, but automatically closes when clicked outside of the window? This is the code I am currently using, which is triggered by a button click: if (response. ...

What is the best way to export a React Material-UI component with two separate styles objects in Material-UI V1?

We are currently utilizing material-ui version 1 and composing Higher Order Components (HOC) with the recompose utility. Our issue arises from having two separate styles objects - one defined within the component itself, and another general style object th ...

The alignment of text is being randomized within Owl-Carousel containers using HTML

I'm facing an issue with the display of my text, and I suspect it might be related to Owl-Carousel. Here is how it's appearing: https://i.sstatic.net/C03TL.jpg Below is the HTML Code: <div class="panel panel-casestudy" data-equalizer-watch= ...

Retrieving information from MySQL using javascript

I am trying to fetch data from a MySQL database using JavaScript. This is the script I have used to load the JavaScript: <script type="text/javascript" src="http://www.domain.de/content/entwicklung/layer.js"></script> Here is the actual scri ...

Repetitive firing of events implemented using AngularJS

Hello, I'm currently trying to trigger an event repeatedly in AngularJS. Below is the code snippet: Here is the HTML code: <li ng-repeat="y in names | limitTo: 6" repeat-done="ratingwithng()"> <a href="<?php echo $this->config-> ...

Is it possible to utilize a WordPress page as a CSS stylesheet?

Is there a way to customize my WordPress theme's CSS through a Page in the backend rather than editing the default style.css file? I've seen it as a page template before but I'm having trouble figuring it out on my own. I'm currently r ...

Guide to downloading a file from a byte base64 in Vue.js

I am dealing with a byte base64 string let data = 'UEsDBBQABgAIAAAAIQBi7...' If I want to download the file from this byte base64 in vue js, what should I do? Any suggestions or solutions would be greatly appreciated :') ...