Hiding an image when pressing on a navbar icon: Tips and tricks

How can I toggle the visibility of an image when the bars icon is pressed on smaller screens, using CSS without JQuery or JavaScript?

I have attempted to hide the image with visibility: hidden; in CSS but it does not work as intended.

Please run this code in a new window and resize the screen to view the effect.

This is my current navbar:

https://i.sstatic.net/RAehe.png

And this is how I want the image to be hidden:

https://i.sstatic.net/Iz5yx.png

.topnav {
  // CSS styles for top nav bar
}

// Other CSS styles

@media screen and (max-width: 600px) {
  // Media query styles for smaller screens
}
<html>

<body>
    <!-- HTML body content -->
  <script>
    function myFunction() {
      var x = document.getElementById("myTopnav");
      if (x.className === "topnav") {
        x.className += " responsive";
      } else {
        x.className = "topnav";
      }
    }
  </script>
  <!--—Navbar and Logo—-->
  <div class="topnav" id="myTopnav">
    // Navbar and logo content here
  </div>

Answer №1

To hide the logo image with the ID "myLogo" when the "responsive" class is applied to the element, you can use the following script:

Live Demo:

function myFunction() {
  var x = document.getElementById("myTopnav");
  var logo = document.getElementById("myLogo");
  if (x.className === "topnav") {
    x.className += " responsive";
    logo.style.display = 'none'
  } else {
    x.className = "topnav";
    logo.style.display = 'block'
  }
}
.topnav {
  border-width: 1px 0;
  list-style: none;
  margin: 0;
  padding: 0;
  text-align: center;
  overflow: hidden;
  background-color: black;
  padding: 10px;
  -webkit-user-select: none;
}

.topnav a {
  display: inline-block;
  padding: 10px;
  margin-left: 40px;
  font-family: 'Open Sans';
  color: white;
  text-decoration: none;
  transition: ease-in-out;
  transition-duration: 0.3s;
  transition-delay: 50ms;
  -webkit-user-drag: none;
  -webkit-user-select: none;
}


/* Hide the link that should open and close the topnav on small screens */

.topnav .icon {
  display: none;
}

.topnav a:hover {
  background-color: rgba(255, 255, 255, 0.884);
  color: black;
  border-radius: 5px;
  transition: ease-in-out;
  transition-duration: 0.4s;
  transition-property: all;
}


/* When the screen is less than 600 pixels wide, hide all links, except for the first one ("Home"). Show the link that contains should open and close the topnav (.icon) */

@media screen and (max-width: 600px) {
  .topnav a:not(:first-child) {
    display: none;
  }
  .topnav a.icon {
    float: left;
    display: block;
  }
  .topnav .icon {
    margin-right: 50px;
    margin-top: 5px;
    transition-property: none;
  }
}


/* The "responsive" class is added to the topnav with JavaScript when the user clicks on the icon. This class makes the topnav look good on small screens (display the links vertically instead of horizontally) */

@media screen and (max-width: 600px) {
  .topnav.responsive {
    position: relative;
  }
  .topnav.responsive a.icon {
    position: absolute;
    right: 80%;
    top: 8px;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
    transition-property: none;
  }
}
<html>

<body>
  <link href="https://fonts.googleapis.com/css2?family=Roboto:ital@1&amp;display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link href="https://fonts.googleapis.com/css2?family=Open+Sans&amp;display=swap" rel="stylesheet">
  <link href="Stylesheetlol.css" rel="stylesheet">
  <!--—Navbar and Logo—-->
  <div class="topnav" id="myTopnav">
    <i class="logo"><img id="myLogo" src="https://t4.ftcdn.net/jpg/02/77/45/89/240_F_277458983_6C5chZcmha2MymgJySMsiqIxJvzxgmVd.jpg" style="height:45px;float:right;border-radius: 3px;-webkit-user-drag: none;"></i>
    <a href="#home" class="active">Home</a>
    <a href="#news">News</a>
    <a href="#contact">Contact</a>
    <a href="#about">About</a>
    <a href="javascript:void(0);" class="icon" onclick="myFunction()">
      <i class="fa fa-bars"></i>
    </a>
  </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

Is there a way to transfer textbox value to ng-repeat in AngularJS?

1) The Industry dropdown menu corresponds with a code textbox. Depending on the selected industry, the code will change accordingly. 2) There is a dynamic feature to add or delete Movie Names and Directors' names. In this table, there are three colu ...

Exploring content within a nested directory on AWS S3

I'm currently experimenting with an ajax request in order to retrieve all image files from a specific subfolder within my S3 bucket. Even though I have set the subfolder to public access using the dropdown menu (view image for reference), I keep enco ...

Revolutionizing the method of projecting a texture onto a halfsphere in three.js projects

I am currently working on a project in three.js where I am trying to project an image onto the inside of a halfsphere. The half sphere is created using the following code: const geometry = new THREE.SphereGeometry(Component.radius, this.resolution, this.re ...

What is the best way to show the current value of a checkbox element in the future?

I want to add multiple checkboxes using this method: $(".btn-sample").on("click", function() { $(".container").append( '<input class="check-sample" type="checkbox" value="'+check_value+'"/>' ); }); The issue I' ...

Add a date to my database using an HTML form

I am having trouble inserting a date into my database using PHP. Everything else inserts correctly, but the date reverts to the default 0000-00-00 as if nothing was entered. I have set the data type for the date field. Here is the code snippet: <?php ...

AngularJS ng-repeat to create a series of radio button options

This particular snippet of code generates two sets of radio buttons. The first set consists of individual radio buttons, while the second set is dynamically created using ng-repeat. Users can select any of the radio buttons by clicking on them directly or ...

Ensure that the contents of the upper and lower divs are appropriately aligned, while maintaining the centered positioning of the

As a complete beginner in the world of HTML and CSS, I am facing a challenge with my code. Here's the HTML snippet: <section class="instructions"> <div class="row"> <div class="instructions-col" ...

JQuery horizontal navbar hover animations

Looking to design a simple navigation bar that displays a submenu when hovering over a link. The issue I'm facing is that the submenu disappears when moving from the link to the submenu itself, which is not the desired behavior. How can this be fixed ...

I am struggling to access the input file data in my controller while attempting to send it over AJAX

Currently, I am utilizing Laravel 3 and incorporating a user comment via AJAX. The issue I'm facing is related to adding images to the comment, as I am encountering difficulty getting the File Data to pass through. Moreover, when I set processData to ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

Navigating through website links while working locally on a localhost server can

After exclusively working on live domains or subdomains in the past, I recently experienced the benefits of working on localhost. Utilizing a Wamp server on my Windows machine, I store my project in C:/wamp64/www/[project_name]. I have always used relativ ...

Tips for preventing text from breaking onto a new line in Safari

I have cforms plugin installed on a WordPress page. Interestingly, the word "required" in Russian appears to consist of two words as per the translation office. While it displays correctly in Firefox, in Safari it breaks and aligns to the bottom left of ...

Is there a way to adjust the time font size according to the dimensions of the time picker?

HTML and CSS .pickthetime { height: calc(var(--vh, 1vh) * 3); width: calc(var(--vw, 1vw) * 25); align-content: center; // center looks better, also tried left to stop it from breaking a new line on Safari on iOS font-weight: 300; } <input cla ...

Using gulp to compile TypeScript is resulting in a directory being generated that we do not want

My goal is to use Gulp to transpile my .ts files located in the /dev directory, and then move the transpiled .js file to a /build directory. The ideal folder structure I am aiming for is as follows: /dev - index.ts /build - index.js However, the curre ...

specific css styles only for Safari and Internet Explorer

Imagine a scenario where I have a div with the class 'x': <div class = 'x' /> This div has some CSS properties and what's interesting is that it appears differently in Safari and the latest version of IE compared to other ...

Implementing location functionality in Nextjs 13+ for both server-side rendering and client-side components

I need help displaying an active link in the header navigation. Previously, I used useRoute() for versions under 13, but it stopped working in version 13 and above. Additionally, useRoute is not mounted when using SSR. To work around this issue, I ensured ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

What is the best way to create an event listener that can identify when a boolean variable switches to true?

Let's say we have a variable var menu_ready = false;. We also have an ajax function that will change menu_ready to true once the ajax operations are completed: // code snippet to set up event listener $(...).load(..., function() { ... menu_r ...

Leveraging the post method in Ajax along with a Perl script and passing parameters

I am struggling to utilize the POST method in XMLHTTPRequest by invoking a Perl script with parameters. Despite confirming the validity of these variables (uName, uProject, etc.), and verifying that write.pl functions properly when parameters are manuall ...

Regular expressions are used for validation purposes

I've been using the regular expression shown below to validate certain text: ^\d+(?:fs|sf)[-+]\d+[hmd]$/ Here are some sample texts I have validated with this regular expression: 20fs-4d 10sf+20m 3fs-2h So far, it's been working we ...