What are the best practices for incorporating CSS within JavaScript?

I have a project to create a Memory Game and I am looking to incorporate a CSS animation for the flip functionality using JavaScript. I want to trigger the animation on click rather than hover. How can I achieve a CSS flip animation with an onclick function in JavaScript?

var card = "<div class='flip-card'><div class='flip-card-inner'><div class='flip-card-front'><button id='button'onclick='Flipfront()'style='width:300px;height:300px; marign:50px; background-image:url(Frontpage.jpg);'></button></div><div class='flip-card-back'><button id='button2' onclick='Flipback()'style='width:300px;height:300px; marign:50px; background-image:url(IMG1.jpg);'></button></div></div></div>"
.flip-card {
  background-color: transparent;
  width: 300px;
  height: 200px;
  border: 1px solid #f1f1f1;
  perspective: 1000px;
  /* Remove this if you don't want the 3D effect */
}

.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.8s;
  transform-style: preserve-3d;
}

.flip-card:hover .flip-card-inner {
  transform: rotateY(180deg);
}

.flip-card-front,
.flip-card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.flip-card-front {
  background-color: #bbb;
  color: black;
}

.flip-card-back {
  transform: rotateY(180deg);
}
<div id="outerbackground">
  <img src="background.jpg" class="backgorund" border="1" id="BG">
</div>
<div id="container"></div>

Answer №1

Expanding on my previous point: instead of relying on the :hover selector, consider using a class like .flipped to manage the flipped status of the card.

In your Flipfront() and Flipback() functions, ensure they accept an argument passed from your markup, called with Flipfront(this) or Flipback(this). This allows you to access the triggering element.

Then, utilize Element.closest() to target the parent .flip-card, using Element.classList.add() or Element.classList.remove() to toggle the flipped class:

var card = "<div class='flip-card'><div class='flip-card-inner'><div class='flip-card-front'><button id='button'onclick='Flipfront(this)'style='width:300px;height:300px; marign:50px; background-image:url(Frontpage.jpg);'></button></div><div class='flip-card-back'><button id='button2' onclick='Flipback(this)'style='width:300px;height:300px; marign:50px; background-image:url(IMG1.jpg);'></button></div></div></div>" 

for (let i = 0; i < 20; i++) {
  document.querySelector("#container").innerHTML += card;
}

function Flipfront(el) { 
  el.closest('.flip-card').classList.add('flipped');
}

function Flipback(el) { 
  el.closest('.flip-card').classList.remove('flipped');
}
.flip-card {
  background-color: transparent;
  width: 300px;
  height: 200px;
  border: 1px solid #f1f1f1;
  perspective: 1000px;
}

.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.8s;
  transform-style: preserve-3d;
}

.flip-card.flipped .flip-card-inner {
  transform: rotateY(180deg);
}

.flip-card-front,
.flip-card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.flip-card-front {
  background-color: #bbb;
  color: black;
}

.flip-card-back {
  transform: rotateY(180deg);
}
<div id="outerbackground">
  <img src="background.jpg" class="backgorund" border="1" id="BG">
</div>
<div id="container"></div>

Answer №2

Did you experiment with dynamically altering classes upon a click event? By clicking on the element, you have the ability to include the class .flip-card-inner and eliminate '.flip-card-front` by utilizing the classlist feature along with its functions

Here's how you can use it:

elem.classList.add("flip-card-inner");

elem.classList.remove("flip-card-front");

Answer №3

Avoid incorporating CSS within JavaScript code. Instead, modify the :hover rule to rely on a class that is toggled when each .flip-card element is clicked.

Additionally, refrain from using outdated onX attributes as they violate the separation of concerns principle. Opt for unobtrusive event handlers instead. The same applies to inline style attributes, which should be moved to an external stylesheet. See the functional example below:

let card = '<div class="flip-card"><div class="flip-card-inner"><div class="flip-card-front"><button id="button"></button></div><div class="flip-card-back"><button id="button2"></button></div></div></div>';
for (let i = 0; i < 20; i++) {
  document.querySelector("#container").innerHTML += card;
}

document.querySelectorAll('.flip-card').forEach(el => {
  el.addEventListener('click', () => el.classList.toggle('flipped'));
});
.flip-card {
  background-color: transparent;
  width: 300px;
  height: 200px;
  border: 1px solid #f1f1f1;
  perspective: 1000px;
}

.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.8s;
  transform-style: preserve-3d;
}

/* update the style by removing :hover */
.flip-card.flipped .flip-card-inner {
  transform: rotateY(180deg);
}

.flip-card-front,
.flip-card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.flip-card-front {
  background-color: #bbb;
  color: black;
}

.flip-card-back {
  transform: rotateY(180deg);
}

#button {
  width: 300px;
  height: 300px;
  background-image: url(Frontpage.jpg);
}

#button2 {
  width: 300px;
  height: 300px;
  background-image: url(IMG1.jpg);
}
<div id="outerbackground">
  <img src="background.jpg" class="backgorund" border="1" id="BG">
</div>
<div id="container"></div>

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

Determine the index of items within an array of objects in Lodash where a boolean property is set to true

I am new to using lodash after transitioning from C# where I occasionally used LINQ. I have discovered that lodash can be utilized for querying in a LINQ-style manner, but I'm struggling to retrieve the indexes of items in an array of objects with a b ...

What impact does reselect have on the visual presentation of components?

I'm struggling to grasp how reselect can decrease a component's rendering. Let me illustrate an example without reselect: const getListOfSomething = (state) => ( state.first.list[state.second.activeRecord] ); const mapStateToProps = (state ...

Vue 3's "<Component :is="">" feature magically transforms camelCase into lowercase

Within my application, I have implemented a feature where users can customize the appearance of social media links on their page by defining which platforms they want to include. Each social media platform is represented by its own component responsible fo ...

The input given to Material UI autocomplete is incorrect, even though the getOptionSelect parameter already exists

I'm currently working on creating my own version of the Google Places autocomplete found in the Material UI documentation. While I have successfully implemented the autocomplete feature and am able to update my component's state with the result, ...

Preventing Clicks on Bootstrap Tabs

Utilizing Bootstrap 3 tabs, I am constructing a step-by-step wizard similar to the layout depicted in the image below. My objective is to restrict direct clicking on the tabs and only permit progression through the use of next/previous buttons. However, I ...

I have expanded the CSSStyleDeclaration prototype, how do I access the 'parent' property?

I have developed some custom methods for CSSStyleDeclaration and implement them like this: A_OBJECT.style.method() ; The code structure is quite simple: CSSStyleDeclaration.prototype.method = function () { x = this.left; ..... etc } Here's my que ...

issue arising from integrating material-ui components with code in a react javascript application

Struggling with integrating code and material-ui components in react jsx, I encountered an issue. Here's the problematic snippet: const icols = 0; const makeTableRow = ( x, i, formColumns, handleRemove, handleSelect) => <TableRow key ...

MUI - Duplicating text within ListItemText

Is there a way to enable text copying from inside the component from material UI? If so, what changes can be made to achieve this? <ListItem key={staff._id} className={background_colour} onClick={par(set_viewing, component, sta ...

Simultaneously scrolling left and fading in with jQuery

I've come across this code that works well in scrolling my divs to the left. However, I'm looking to add a fading effect while they are scrolling. Is there a way to achieve this? $('div#line1').delay(1000).show("slide", { direction: "r ...

The UI5 application encounters issues when it is invoked as a component

My UI5 Application works perfectly fine when called through index.html, but breaks (404 errors, failed to load resources, etc) when I try to call it as a Component. Both the Caller and Callee applications are on Gateway. Here is the folder structure of th ...

What is the way to create the appearance of a hand or arrow hovering over my "X" while I am closing out my Div using jQuery?

Hey there, I've got a handle on closing the div using a "p" tag in jQuery. The code snippet for that is provided below. However, I'm looking to change the cursor over the "X" to an arrow or hand symbol, similar to what you'd see with an "a" ...

Is it possible to validate the accept attribute?

Does HTML5 accept the accept attribute for validation? In other words, if we use <input type="file" name="pic" accept="image/jpg" />, will it only accept jpg files? Or do I need to use JavaScript for validation? ...

Could someone help me understand this JavaScript code where a function takes an object as a formal parameter?

Within a Vue component's methods, I came across the following code snippet defining a function: methods: { onEditorChange({ editor, html, text }) { console.log('editor change!', editor, html, text) this.content = html ...

How can I use jQuery to display an alert when clicking on a child element within another

I have a code snippet that triggers an alert when clicking on a specific element: $("#resultsBox").click(function (event) { console.log('a'); }); Now, I want to modify it so that the alert only appears when clicking on 'li' el ...

Is it possible to integrate Express 4 standalone middleware into an Express 3 application?

While I am not yet prepared to upgrade my Express 3 installation to Express 4, I am interested in utilizing some of the enhanced components in Express 4, such as express-session and compression. I have experimented with implementing these upgrades and eve ...

``There is an issue with the onsubmit property that prevents the opening of

I have encountered an issue with my forms that has me stumped. Despite searching online for help, I can't seem to figure out why my implementation is not working as intended. The concept is straightforward. I've embedded a form within a JSP page ...

Unable to view the refreshed DOM within the specifications after it has been altered

For my current project, I am working on writing a functional spec that involves using Mocha/JSDOM and making assertions with 'chai'. The specific use case I am tackling is related to the function called updateContent: When this function is exec ...

Issues with the JavaScript, HTML, and CSS Counter Implementation

Is there anyone who can assist me in making this code (available at https://jsfiddle.net/hmatrix/v3jncqac/) function properly? Purpose: My goal is to develop a counter that increments by specified values. My HTML: <body onload="incrementCount(10)"> ...

How to use AngularJS to collapse various panels with unique content

Hey everyone, I'm working on developing a collapsible panel using Angular. The panel should consist of a header and body to display the content. The desired behavior is that when a button is clicked, the content collapses down, and clicking the same b ...

Creating a new web application, I require a loading overlay to appear during transitions between pages

I've checked high and low, but I can't seem to find the solution! My webapp has a page that is bogged down with data causing it to load slowly. Is there a way to display a loading div while transitioning to the next page? Perhaps something like ...