Adjust Navbar Header Color Based on Screen Size

I am completely new to front-end development. I am in the process of building my own responsive website using Bootstrap 3.

One issue I am facing is that when I resize my browser window to simulate a phone screen, I want the navigation bar color to change to white upon clicking the Menu Icon.

Currently, the header stays transparent on page load and changes to white while scrolling, as intended. However, when I click the hamburger menu icon, the collapsible nav header drops down with the menu items but the background remains transparent, causing the menu items to overlap the content below.

I have attempted to write a script to address this issue, but it doesn't seem to be working. Can anyone provide any suggestions?

<script>
    var windowsize = $(window).width();
    $(window).resize(function() {
        windowsize = $(window).width();
            if (windowsize < 440) {
                $("#myNavbar").click(function () {
                  $(".navbar-header").css({"background-color": "#ffffff", "-webkit-box-shadow": "0px 1px 4px 0px rgba(180, 180, 180, 0.5)", "-moz-box-shadow": "0px 1px 4px 0px rgba(180,180,180, 0.5)", "box-shadow": "0px 1px 4px 0px rgba(180,180,180, 0.5)"});
                });
            };
      });
</script>

Answer №1

To achieve the desired outcome, incorporate Media Queries into your CSS file.

@media screen and (max-width: 300px) {
    nav {
        background-color: #ffffff;
    }
}

Answer №2

By implementing a click event to change the color, there is no need for a window resize function.

<script>
    $("#myNavbar").click(function () {
        windowsize = $(window).width();

        if (windowsize < 440) {
            $(".navbar-header").css({"background-color": "#ffffff", "-webkit-box-shadow": "0px 1px 4px 0px rgba(180, 180, 180, 0.5)", "-moz-box-shadow": "0px 1px 4px 0px rgba(180,180,180, 0.5)", "box-shadow": "0px 1px 4px 0px rgba(180,180,180, 0.5)"});
        }
    });

</script>

To make the CSS dynamic, it would be recommended to use a class. Adjusting the JS code to

$(".navbar-header").addClass("active");
allows you to define the active class in your CSS files.

Answer №3

Utilizing media queries is an effective method to ensure that CSS properties adapt based on the screen size.

If you're looking for code that fits your requirements, consider the following:

.header-section {
    @media only screen and (max-width: 760px) {font-size: 16px;}
}

This example adjusts the font size of the header section when the screen width is 760px or below.

Answer №4

To achieve this effect, I would use a combination of JavaScript and CSS media query.

JavaScript:

$("#myNavbar").click(function() {
    $(".navbar-header").toggleClass('.active-nav')
});

CSS:

@media only screen and (min-width:440px) {
    .navbar-header.active-nav {
        background-color: #ffffff;
        -webkit-box-shadow: 0px 1px 4px 0px rgba(180, 180, 180, 0.5);
        -moz-box-shadow: 0px 1px 4px 0px rgba(180, 180, 180, 0.5);
        box-shadow: 0px 1px 4px 0px rgba(180, 180, 180, 0.5);
    }
}

Answer №5

Here is a helpful tip for you:

$("#myNavbar").click(function () {
  $(".navbar-header").addClass("navbar-header-mobile");
});
/* For Extra Small Devices like Phones */ 
@media only screen and (min-width : 480px) {
  .navbar-header-mobile {
    background-color: #ffffff;
    -webkit-box-shadow: 0px 1px 4px 0px rgba(180, 180, 180, 0.5);
    -moz-box-shadow: 0px 1px 4px 0px rgba(180,180,180, 0.5);
    box-shadow: 0px 1px 4px 0px rgba(180,180,180, 0.5);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If you want, you can also add code to remove it on the phone.

Answer №6

Resolved the issue by making changes not only to the header color, but also to the collapsible menu background. I applied a similar logic used for the header color change to capture the click function of the collapsible navigation bar and toggle the colors accordingly. Here is the finalized code snippet:

<script>
  $(function (){
    $(".navbar-toggle").click(function() {
        if ($(window).width() < 440) {
            $(".navbar-collapse").toggleClass("menuActive");
            $(".navbar-header").toggleClass("menuActive");
        } 
    });
  }); 
</script>

Answer №7

When the screen resolution is less than 440, clicking on the navbar will change its color to white:

<script>
      $('.navbar').click(function() {
           $(this).toggleClass('open');
      });
</script>
@media only screen and (max-width: 440px) {
    .navbar.open {
      background-color: #ffffff;
      -webkit-box-shadow: 0px 1px 4px 0px rgba(180, 180, 180, 0.5);
      -moz-box-shadow: 0px 1px 4px 0px rgba(180,180,180, 0.5);
      box-shadow: 0px 1px 4px 0px rgba(180,180,180, 0.5);
    }
}
<div class="navbar"></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

Creating a dynamic directive in AngularJS: Learn how to add or remove it from the DOM based on specific conditions

Suppose I have a customized modal directive that looks like this: return { restrict: 'E', templateUrl: 'modal.html', scope: { modalContent: "&", modalOpen: "&" } } And in the HTML: <ng-modal modal-content="co ...

Included Image Hyperlink with Limited Clickability in HTML

When trying to turn my image into a hyperlink, I enclosed it with the tag. Oddly enough, only the lower portion of the image is responsive as a link. The upper part seems unresponsive. Here's the code snippet I used: <a href="link-here"& ...

What could be causing the show button to change its style every time I click it?

I'm a beginner in the world of JavaScript. I have been working on customizing the "show more" button and encountered an issue. I managed to add text and a down arrow below the button, but when I click it, another button labeled "I don't know how ...

Encountering issues with importing a module from a .ts file

Although I have experience building reactJS projects in the past, this time I decided to use Node for a specific task that required running a command from the command line. However, I am currently facing difficulties with importing functions from other fil ...

Interval function not initiating properly post bullet navigation activation

Currently, I am experiencing an issue with my custom slider where the auto sliding set interval function is not working after using the bullet navigation. Despite trying to implement "setTimeout(autoSlide, 1000);", it doesn't seem to be resolving the ...

Unable to invoke a custom hook within another custom hook in a React application

I've developed a React application using create-react-app. Currently, I'm working on creating a custom hook that integrates with the Microsoft Authentication Library (MSAL). MSAL provides a custom React hook that I want to utilize within my own ...

Express server is receiving undefined post parameters from Axios in Vue, even though they are clearly defined in Vue

Within my code, I am utilizing an <img> element as shown below: <img v-bind:word = "thing" @click="action" align="center" src="../assets/pic.png"/> Alongside, there is a method structured in this manner: ...

Issue: [ng:areq] The parameter 'PieController' is not properly defined, it is currently undefined

Why am I getting an error when using ng-controller='DoughnutCtrl' in a dive? Error: [ng:areq] Argument 'DoughnutCtrl' is not a function, got undefined Here is my Chart.js code: 'use strict'; angular.module('portfoli ...

Issues persist while attempting to save sass (.scss) files using Atom on a Mac

When attempting to work with sass files, I encountered an error message every time I tried to save the file: Command failed: sass "/Users/bechara/Desktop/<path of the file>/test.scss" "/Users/bechara/Desktop/<path of the file>/test.css" Errno: ...

Issue with Jquery live event not triggering after successful execution

Encountering an issue where jquery live is not triggering on ajax success. Take a look at my link_to function. <%= link_to image_tag("cross.png"), patient_recurrence_detail_path(params[:id],f.object.id), :remote => true, :class => 'delete_re ...

How can I eliminate the tiny white square located beneath the scrollbar track?

`::-webkit-scrollbar{ width: 12px; } body::-webkit-scrollbar-track{ background: #f1e9e9; border-radius: 10px; margin-block: 0.1875rem; } ::-webkit-scrollbar-thumb{ background-color: #582965; border-radius: 10px; border: 3px so ...

What is the best way to import JSON functionality into Javascript specifically for use with Internet Explorer

I am facing an issue with loading JSON feature in JavaScript for IE8 while in compatibility mode. After receiving advice, I decided to utilize douglascrockford/JSON-js to enable JSON support on outdated browsers. To tackle this problem, I created a new f ...

JavaScript and jQuery validation issues persisting

Here is the HTML code I am using: <script src="js/validate.js"></script> <label>FIRST NAME:</label> <td> <input type="text" class="firstname" id="firstname" onKeyUp="firstname()" /> </td> <td> <label id=" ...

The Table and Div elements do not have identical widths when set to 100%

I am facing an issue with a Div and Table placed inside a container. Although they are meant to completely fill the container, occasionally there is a one pixel difference which can be quite annoying. I have prepared a test case and attached a screenshot h ...

Navigate to the chosen item in material-ui scroll bar

Currently, I have a list created using material-ui which contains numerous items and displays a scrollbar due to its size. I am looking for a way to automatically scroll to the selected item within the list. Does anyone have any suggestions on how I can a ...

Utilizing Snowpack to implement private class methods in JavaScript

In my front-end development, I utilize private JavaScript class methods and Snowpack for my workflow. Unfortunately, I've encountered an issue with Snowpack (as of v2.15.0-pre.5) not supporting private class methods. When trying to build using snowpa ...

What are the steps for releasing a Next.js app as an npm package?

Currently, my web application is developed using Next.js. I am interested in distributing it as an npm package for others to utilize in their projects. Despite my efforts to search and seek assistance through Google, I have not come across any valuable ins ...

How to Align Navigation Searchbar in Center When Bootstrap is Collapsed

I am attempting to center my search bar when it is collapsed. Currently, it appears like this: As you can see, the links are centered, but not the search bar. This is the existing HTML structure: <!-- Navigation Bar Start --> <div class ...

Colored stripe on a horizontal menu

I am attempting to design a page header with a menu that resembles the image provided below. https://i.sstatic.net/623eH.png As I construct the navigation, each link area (highlighted in blue) is represented by an <li>. However, I am encountering a ...

The screen reader seems to be malfunctioning as soon as I include this particular code

//Finding the height of the header let headerHeight = document.querySelector('header'); let height = headerHeight.offsetHeight; //Adjusting the #navbarNav's top margin to accommodate the header let nn = docu ...