Modify CSS class if user is using Internet Explorer version 10 or above

I am attempting to modify the CSS of 2 ASP controls using jQuery specifically for users accessing the site with Internet Explorer 10 or 11. This adjustment is necessary because IE10 onwards, conditional comments are no longer supported. My approach to achieving this is as follows:

<script>
    $(document).ready(function () {         
        if ($.browser.msie && $.browser.version === 10 || $.browser.msie && $.browser.version === 11) {

            alert('testIf');

            $("#txtUsername").removeAttr('loginInput');
            $("#txtPassword").removeAttr('loginInput');

            $("#txtUsername").css({
                "width": "284px",
                "border": "0px",
                "border-top": "1px solid #646464",
                "border-bottom": "0px #646464 solid",
                "border-left": "solid #646464 4px",
                "height": "33px",
                "background-image": "url(./Images/login-icon.png)",
                "background-repeat": "no-repeat",
                "padding-left": "16px",
                "float": "left",
                "display": "block",
            });

            $("#txtPassword").css({
                "width": "284px",
                "border": "0px",
                "border-top": "1px solid #646464",
                "border-bottom": "0px #646464 solid",
                "border-left": "solid #646464 4px",
                "height": "33px",
                "background-image": "url(./Images/login-icon.png)",
                "background-repeat": "no-repeat",
                "padding-left": "16px",
                "float": "left",
                "display": "block",
            });
        } else {
            alert('testElse');
        }
    });
</script>

I have implemented 2 textboxes like so:

        <asp:TextBox CssClass="loginInput loginUsername" TabIndex="1" ID="txtUsername" autocomplete="off" AutoCompleteType="Disabled" runat="server"></asp:TextBox>

        <asp:TextBox CssClass="loginInput loginPassword" TabIndex="2" ID="txtPassword" textmode="Password" runat="server"></asp:TextBox>

This is my modified CSS (with width being the only change from the original):

.loginInput {
    width: 285px;
    border: 0px;
    border-top: 1px solid #646464;
    border-bottom: 0px #646464 solid;
    border-left: solid #646464 4px;
    height: 33px;
    background-image: url(./Images/login-icon.png);
    background-repeat: no-repeat;
    padding-left: 16px;
    float:left;
    display:block;
}

.loginUsername {
    margin-top: 15px;
    background-position: 271px 9px;
}

.loginPassword {
    background-position: 271px -75px;
}

In Internet Explorer, the only necessary modification is altering the width for the CSS to display correctly. I've attempted moving the JS outside the document ready function but to no avail. Could someone provide guidance on what I might be doing incorrectly and suggest a way forward.

Answer №1

The issue lies in your browser detection code. When running the code in a JSFiddle, you will consistently end up in the else block, even when using Internet Explorer 11.

As suggested by Archer, consider detecting the browser on the server side and serving different CSS to the client.

Additionally, why are you using this:

 $.browser.msie && $.browser.version === 10 || $.browser.msie && $.browser.version === 11

Instead, try using this:

$.browser.msie && $.browser.version > 9 

Answer №2

Discover Conditionizr, a tool specially designed for managing environment detects. It provides an Object that allows you to easily handle your tests. Take a look at the IE10 detect. Keep in mind that we're utilizing UA sniffing to disregard the Mobile version of IE10, as targeting Mobile IE requires different considerations due to their differences. Also, take a look at the IE11 detect.

conditionizr.add('ie10', [], function () {
  var version = false;
  /*@cc_on
    if (/^10/.test(@_jscript_version) && /MSIE 10\.0(?!.*IEMobile)/i.test(navigator.userAgent))
    version = true
  @*/
  return version;
});

You can use it to add a class like this (note ['class']):

conditionizr.add('ie10', ['class'], function () {
  var version = false;
  /*@cc_on
    if (/^10/.test(@_jscript_version) && /MSIE 10\.0(?!.*IEMobile)/i.test(navigator.userAgent))
    version = true
  @*/
  return version;
});

This also gives you complete Object access for inline JavaScript development:

if (conditionizr.ie10) {
  // Handle IE10 scenarios...
}

Furthermore, you can run callbacks with ease:

conditionizr.on('ie10'[, callback]);

Answer №3

To identify this issue without resorting to conditional comments or User Agent sniffing, you can utilize conditional compilation:

<script type="text/javascript">
    var isIE10 = false;
    /*@cc_on
        if (/^10/.test(@_jscript_version)) {
            isIE10 = true;
        }
    @*/
    console.log(isIE10);
</script>

Once the above code is executed, you can check for Internet Explorer 10 at any point:

if (isIE10) {
    // Code specific to Internet Explorer 10
}

For further information, refer to: How can I detect IE10 from JS when browser mode is IE9?

Update:

function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

Example:

if (isIE () == 8) {
 // Action for IE8
} else {
 // Handle other versions of IE or non-IE browsers
}

or

if (isIE () < 9) {
 // Handling IE versions below 9
} else {
 // Dealing with IE 9 and newer versions or non-IE browsers
}

or

if (isIE()) {
 // In case of IE
} else {
 // For other web browsers
}

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

When I switch to mobile view, my navigation menu vanishes

Currently in the process of creating a website using WordPress, specifically with a divi theme and utilizing a windows operating system. It seems that everything appears correctly on desktop, however when resizing the window or viewing the site on a mobile ...

Guide to defining a conditional statement in a Nuxt.js application

I am working on displaying data from the Wordpress API in a Nuxt.js project. I am trying to organize the data by category, for example where ('post.category ', '=', 'categoryName '). Can anyone help me with the syntax in Vue.j ...

Page not found: unique error on alternate route

My website has different paths and pages in hbs format, such as root, help, and 404. The problem arises when I navigate to localhost:3000/wrong, the site displays correctly, but when I try localhost:3000/help/wrong, the CSS is not applied to the 404 page b ...

Using jQuery to populate tables

Here is a table I am working with: <table class="table table-hover"> <thead> <tr> <th>Person</th> <th>Ethereum Address</th> ...

Importing modules using relative paths results in failure due to module not being found, whereas employing absolute paths

I have been encountering this problem for a considerable amount of time and have made multiple attempts to resolve it. I am currently working on the development of my discord.js bot and recently switched from TS back to JS due to certain complications I fa ...

Change the term to its corresponding translation

I have developed an Ionic Multilingual App that includes a select feature. Within this select, choosing a specific option disables certain page elements. However, I am facing an issue where one of the elements needs to change its text based on the selected ...

Exploring the TypeScript compiler API to read and make updates to objects is an interesting

I'm delving into the world of the typescript compiler API and it seems like there's something I am overlooking. I am trying to find a way to update a specific object in a .ts file using the compiler API. Current file - some-constant.ts export co ...

What is the significance of declaring a constant array in JavaScript?

Does declaring an array as a constant in JavaScript prevent it from changing size, or does it mean that the values inside the array cannot be modified? handleClick(i) { const squares = this.state.squares.slice(); squares[i] = 'X'; this.setState( ...

sending data from angular controller to a node server

Having trouble with my Angular controller that posts to the node server. The function triggering the post is giving me a 404 (Not Found) error when running it. I've tried rewriting the post multiple times but can't seem to locate the issue. If ...

Is there a way to customize the progress bar percentage in Ant design?

I am currently utilizing React JS and importing the Ant Design progress component (refer to https://ant.design/components/progress/). However, I am facing difficulties in dynamically editing the percentage of the progress bar using JavaScript after it has ...

Showing all elements on page load that are currently being filtered out in React

I've created a page that displays a grid of images with various details like title, description, author, and more. All this data is being pulled from my SQL table (referred to as marketplaceData). To enhance user experience, I added a search bar to f ...

Sending a parameter to a different function (on a separate webpage)

At the start of my webpage, there are two radio buttons on the first page, each with its own value. Upon clicking a link to move to the second page, a for loop is activated to grab the value of the selected button. The script has been tested and works as e ...

Is there a way to ensure uniform font display across all browsers?

Is there a way to ensure consistent font display across all browsers? I am facing an issue with font consistency on my webpage. While browsers like Internet Explorer Edge and 11, Chrome, and Firefox display the desired font correctly, Internet Explorer 8 ...

Infinite scrolling with Jquery: Loading dynamic content seamlessly from external websites

Hey there! I recently started using this cool jQuery plugin called jquery-endless-scroll. Here's a snippet of my code: $(function() { $('#list').endlessScroll({ pagesToKeep: 10, fireOnce: false, insertBefore: "#list div:first ...

Sockets causing a blockage in the Express server

Encountering an issue while setting up an express server with Sockets (using the socketcluster-server module). After sending around 20 http requests, the express server gets blocked, leading to the Sockets (client) reporting a connection depletion. Has an ...

jQuery's :last selector allows you to target the last

I need assistance with my jQuery code $('#share_module:last').css("background-color","red"); Unfortunately, it is only affecting the first #share_module Here is an example of the HTML structure: <div id = "share_module" class = "id of the ...

Transferring Data to EJS Template

I have been facing a challenge in passing a value from a POST route to an EJS file for display. Despite trying various methods like redirecting, sending, and rendering the results, the data won't make its way to the EJS file. Below is the POST route ...

The jQuery scripts are having trouble cooperating

Currently, I am in the process of developing a website. The main focus at the moment is on creating a responsive menu and incorporating jQuery scripts. However, I seem to be facing some challenges in getting everything to work seamlessly together. Each scr ...

How to find and pair up custom data attributes that are unfamiliar?

Is there a method to select elements with unspecified custom data attributes? When I say unspecified, I am referring to an element that could appear like this: <div data-unknown="foo"></div> or <td data-someOtherCustomDataAttribute="bar"& ...

What is causing the CORS error with JQUERY and JQM?

My HTML5 page is set up without any jQuery and has no CORS error, as shown below: <!DOCTYPE html> <HTML> <button type="button" onClick="getBase64FromImageUrl()">Click Me!</button> <img id="preview1" crossorigin="anonymous" src=" ...