What are the techniques for implementing an if statement in CSS or resolving it through JavaScript?

Demo available at the bottom of the page

Within my code, there is a div called #myDiv that defaults to an opacity of 0.

Upon hovering over #myDiv, the opacity changes to 1. See the CSS snippet below:

#myDiv {
  opacity: 0;
}

#myDiv:hover {
  opacity: 1;
}

Additionally, there is an


tag inside the div with a default width of 0 and transitions to 100% on hover:

hr {
  width: 0;
  -webkit-transition: all 0.5s ease;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  transition: all 0.5s ease;
}
#myDiv:hover hr {
  width: 100%;
}

A script on the website detects mobile users and sets the opacity to 1 if the div is visible without triggering the hover effect.

I am looking for a way to apply the


effects on mobile devices. While I initially considered using an if statement in CSS, it's not possible. The best solution may involve JavaScript. Here is what I had in mind:

if (#myDiv.opacity == 1) {
  hr {
    width: 100%;
  }
}

Since this cannot be achieved with CSS alone, I'm seeking guidance on how to implement this functionality using JavaScript, as I have limited experience with it.

To see a working demo on desktop, please visit: My Work and hover over the project section. How can I replicate this behavior on mobile?

Answer №1

Sorry, but if statements cannot be used in plain CSS. However, you can achieve basic detection using a media query:

@media screen and (max-width:767px){
  hr {
    width: 100%;
  }
}

This media query targets screens with a maximum width of 767 pixels, which is slightly smaller than an iPad. Feel free to adjust the settings as needed.

Alternatively, you can utilize JavaScript for this task. Look for a script that identifies mobile users and adds the class isMobile to the <body />. With this class added, you can then apply styles like so:

.isMobile hr {
    width: 100%;
}

If you only want to make changes when an element is in view, JavaScript must be used to detect this. There are various snippets available for accomplishing this. You can follow a similar approach by adding a class such as isInView.


In both scenarios, CSS is responsible for the styling while JavaScript serves as a support. CSS handles the visual aspects, so it's best to communicate styling instructions through CSS classes even when using JS.

Answer №2

Consider utilizing media queries to adjust the styling based on screen size, and you may find that removing your JavaScript for opacity is a viable solution ;)

@media screen and (max-width:767px){
  #myDiv {
    opacity: 1;
  }
  #myDiv hr {
    width: 100%;
  }
}

Edit: If you also need to check if an element is in view using JavaScript, instead of setting opacity directly to 1, add a class to #myDiv and update the CSS accordingly:

hr {
  width: 0;
  -webkit-transition: all 0.5s ease;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  transition: all 0.5s ease;
}

#myDiv {
  opacity: 0;
}

#myDiv:hover, #myDiv.mobile {
  opacity: 1;
}

#myDiv:hover hr, #myDiv.mobile hr {
  width: 100%;
}

This method allows you to manage the style changes in a consistent manner across different devices by simply adding a class ;)

Answer №3

If you encounter any issues, feel free to reach out for assistance as I am currently away from my computer desktop.

jQuery can be utilized in this scenario. Check if the opacity of an element with class 'test' is equal to 1, and if so, set the width of the <hr> element to 100%.
if ($('.test').css('opacity') === '1') {
    $("hr").css("width", "100%");
}

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

What is the operational mechanism behind drag and drop page builders?

I am currently delving into my inaugural MERN project, where the functionality requires specific components (such as a checkbox to-do list, images, text, etc...) that empower users to construct various pages, larger multi-checkbox aggregation lists, and be ...

Methods for retrieving a file within a nodejs project from another file

Currently, my project has the following structure and I am facing an issue while trying to access db.js from CategoryController.js. The code snippet I have used is as follows: var db = require('./../routes/db'); Upon attempting to start the No ...

Determine whether the elements within an array are present on the webpage. If they are, display an alert. If not, reload the page

Initially, I had a userscript designed to search for a specific string within a webpage. If the script failed to locate the string, it would refresh the page after 4 seconds: var item = 'apple'; if(document.body.innerHTML.toString().indexOf(item ...

Would someone be able to clarify the purpose of this await useState React code?

Recently, I came across some React code that directly modifies the state, which goes against what I was taught. However, when I attempted to update it properly, the functionality broke. Clearly, an issue needs to be fixed, but before diving in, I'd li ...

retrieving the configuration settings from my customized service

When attempting to access my custom service within its config property in order to inject an HTTP interceptor, I am encountering the following issue: angular .module("common.services") .factory("redirectService", [" ...

The JavaScript date picker is malfunctioning in the HTML editor, but it functions properly in Fiddle

I have a working format available in a JS fiddle. Here is the code I have used on my demo site: I created a new folder named "js" and placed datepicker.js inside it, then linked it in my HTML like this: <script type="text/javascript" src="js/datepicke ...

Trouble arises when jquery's "position().top" clashes with the CSS3 property "transform: scale()"

Currently, I am working on adding a font resizer feature to my editing tool. To implement this, I made some changes to the text elements where their origin is now set to the bottom left corner. The normal version of the tool works perfectly fine, but when ...

Get the object method within an AJAX success callback

Is there a way for me to access the FileUploader.prototype.saveImage() method in my code? Here is an example snippet: function FileUploader(object) { this.checkInputs(object); if (this.isImageSelected()) { this.beforeInit(object); ...

Empty Data Table Search After Refresh While Filter Remains Active

After testing the data tables library using their example code in a jsfiddle, it seems like there might be a bug. To recreate the issue, follow these steps: Open the JS Fiddle link https://jsfiddle.net/t4rphnuc/ Click "Run" In any footer search box, fil ...

Improving Material UI Responsiveness: A Comprehensive Guide

Could someone please help me resolve the overflow issue in my UI? You can view the overflow here. The second image explains the reason behind it, which you can see here. I am currently working on fixing my UI using React and Material UI. When checking the ...

Refresh database records

I am currently using grails and I am exploring ways to update my database table utility by selecting values from two drop down menus. These drop down menus are populated with values from the database based on user selections from another drop down menu. My ...

What are the steps to resize a YouTube embedded video?

I am currently attempting to use a YouTube video as the background for breadcrumbs on my website. However, I am facing an issue with setting the video width to cover the full screen. The image below shows that the video is displayed in the center of the if ...

Transform a 2-dimensional array of numbers into an array of objects labeled with a "row" index

Today my brain seems to be in full-on "fart" mode. Struggling to find a clean solution for this task without resorting to an ugly loop or recursion. I have a 2D array of numbers that looks like this: const layoutMatrix = [ 1, [1], [0.5, 0.5], [0.2 ...

What is the best way to incorporate text transitions using jquery?

Recently, I've come across this code snippet: $('#slider_title').text(var); This line of code successfully adds the text stored in a variable to the paragraph identified by the id "slider_title". And now, my goal is to smoot ...

How to add additional text after a particular line within a string containing multiple lines using JavaScript

What is the best way to add a new string after line 2 in a multi-line JavaScript string? ...

Using jQuery, remove any white spaces in a textbox that are copied and pasted

There is a textbox for entering order IDs, consisting of 7 digits. Often, when copying and pasting from an email, extra white spaces are unintentionally included leading to validation errors. I am looking for a jQuery script to be implemented in my Layout ...

Ways to address time discrepancies when the countdown skips ahead with each button click (or initiate a countdown reset upon each click)

Every time I click my countdown button, the timer runs normally once. But if I keep clicking it multiple times, it starts skipping time. Here are my codes: <input type="submit" value="Countdown" id="countdown" onclick="countdown_init()" /> <div i ...

Strategies for preventing the appearance of empty rows associated with unused <tr> elements

I currently have multiple asp.net panel controls that I am displaying using an html table. These panels are initially set to visible = false, but depending on the data retrieved from the database, some of the panels will be made visible. The issue arises w ...

Issue with window.localStorage.setItem not functioning properly on mobile devices

Currently, I am developing an HTML5 mobile application with jQuery Mobile. Below is a snippet of my code: $(document).on("click","#send_mobile_number",function(){ var mobile = $('#mobile_number').val(); var user_id = sessionStorage.get ...

Negatives of utilizing two different UI libraries within a single react project?

I have been contemplating a decision that may be considered unconventional from a technical standpoint. Despite my search efforts, I have not come across any explanation regarding the potential drawbacks of this decision. Imagine creating a React website ...