CSS based on Media Query width is not being applied after content has been rewritten by an AJAX call

Check out this website (created using Zurb Foundation Framework) where, on screens wider than 425px, there is a row of books displayed on a background image resembling a bookshelf within a specific div element.

However, when viewing the page on a phone or a smaller browser window with a width below 425px, the background image disappears and the inner divs transform into separate rows for each book.

This is achieved through CSS styling:

#homeBookshelfRow {
    margin-top:50px;
    background:url(../img/homepage/hmpg-mini-shelf/hmpg-shelf.png) bottom center no-repeat; 
    height:160px;
    padding:19px 0 0 11px;
    text-align:center;
}

#homeBookshelfHeadline {
    display:none;   
}

.phoneBookGroup {
    margin:0;
    padding:0;
    display:inline;
}

#homeBookshelfRow .phoneBookGroup .homebook {
    padding-right:10px; 
    cursor:pointer;
}

Additionally, there are styles defined based on the screen width:

@media only screen and (max-width: 425px) {  
    #homeBookshelfRow {
        background:none;
        height:auto;
        margin:0 0 20px 0;
    }

    #homeBookshelfHeadline {
        display:block;  
        font-family: 'Open Sans Condensed', sans-serif;
        font-size:2.25em;
        color:#b11717;
        padding:0;
        margin:0;   
    }

    .phoneBookGroup {
        display:block;
        margin-bottom:10px;     
    }


}

The HTML structure responsible for displaying the books is organized in such a way to adapt to different screen sizes:

<div class="row" id="homeBookshelfRow">
    <p id="homeBookshelfHeadline">
    Bookshelf
    </p>

    <div class="phoneBookGroup">
        <img src="/bookshelf/HCcovers/21_199.jpg" alt="Justice for Sara" width="88" height="141" rel="21" data-urlname="Justice-for-Sara" class="homebook">
        <img src="/bookshelf/HCcovers/22_199.jpg" alt="Storm Season" width="88" height="141" rel="22" data-urlname="Storm-Season" class="homebook">
        <img src="/bookshelf/HCcovers/23_199.jpg" alt="Wishing Moon" width="88" height="141" rel="23" data-urlname="wishing-moon" class="homebook"></div>
    <div class="phoneBookGroup">    
        <img src="/bookshelf/HCcovers/18_199.jpg" alt="Watch Me Die" width="88" height="141" rel="18" data-urlname="Watch-Me-Die" class="homebook">
        <img src="/bookshelf/HCcovers/19_199.jpg" alt="Slices of Night" width="88" height="141" rel="19" data-urlname="Slices-of-Night" class="homebook">
        <img src="/bookshelf/HCcovers/17_199.jpg" alt="Blood Vines" width="88" height="141" rel="17" data-urlname="blood-vines" class="homebook"></div>
    <div class="phoneBookGroup">    
        <img src="/bookshelf/HCcovers/16_199.jpg" alt="Breakneck" width="88" height="141" rel="16" data-urlname="breakneck" class="homebook">
        <img src="/bookshelf/HCcovers/24_199.jpg" alt="Chances Are" width="88" height="141" rel="24" data-urlname="chances-are" class="homebook">           
    </div>   
</div>

The page functions correctly initially, but after Ajax calls update the book images and sidebar content, the width-specific CSS rules get overridden by default rendering styles in all browsers.

To address this issue and ensure consistent styling, you may need to revisit how the CSS is applied and possibly adjust the script handling the AJAX requests accordingly.

$('.homebook').click(function() {
    var id = $(this).attr('rel');
    var urlname = $(this).attr('data-urlname');

    $('#bigHomeBook').attr( 'src' , '/bookshelf/hmpg-mini-shelf/large/'+id+'.jpg'  );
    $('#bigHomeBookLink').attr( 'href' , '/bookshelf/' + urlname );

    $.ajax({
        url: 'inc/home_book_ajax.php?bID=' + id,
        success: function(data) {
            if (data == 'bad') {

            } else {
                $('#rightSidebar')
                    .html('')
                    .addClass('reviewRed')
                    .html(data);
            }
        }
    }); 
});

Answer №1

It's important to specify max-device-width in your media queries to prevent the browser from adjusting the width based on content, which can lead to scrolling or scaling issues not matching your intended style rule.

To learn more about the difference between max-device-width and max-width for mobile web, check out this informative discussion: What is the difference between max-device-width and max-width for mobile web?

UPDATE: For additional insights and specific quirks related to iPhones, I recommend exploring this resource: http://www.quirksmode.org/blog/archives/2010/09/combining_meta.html

If you're interested, I've created a useful detector to determine actual numbers, accessible here: http://jsfiddle.net/JztA4/2/

<html>
<head>
  <script>
    var s = "";
    for (var i = 0; i < 4096; i++) {
      var dev = i % 2 ? "device-" : "";
      s += "\n @media all and ( min-" + dev +
        "width:" + i / 2 +
        "px) {\n#" + dev + "width:before {\ncontent:'" + Math.floor(i / 2) +
        "';\n}}\n";
    }
    s += "\n#sanity:before{content:'youbet';display:inline;}\n";

    l = document.createElement("link");
    l.setAttribute("type", "text/css");
    l.setAttribute("rel", "StyleSheet");
    l.setAttribute("href", "data:text/css," + s);
    document.head.appendChild(l);
  </script>
</head>

<body>
<ul>
    <li>sanity: <span id="sanity"></span>
    </li>
    <li>width: <span id="width"></span>
    </li>
    <li>device-width: <span id="device-width"></span>
    </li>
</ul>
</body>
</html>

Keep in mind that using data URIs may not be compatible with older browsers, so it's recommended to incorporate the styles into a regular CSS sheet or style elements instead.

I'm not actively updating dynamic site results currently, but feel free to enhance the jsfiddle or contribute to this discussion if you have insights to share.

Answer №2

I encountered a similar issue where my @media CSS styles were not being applied after an Ajax update.

In my case, I work with ASP.NET and Telerik controls, and the workaround that worked for me was to turn off page head updates during Ajax requests:

Check out this link for more information: www.telerik.com/help/sitefinity/developer-manual/radajax.net2-telerik.webcontrols.radajaxutils.radajaxcontrol-enablepageheadupdate.html

I hope this solution helps you or others facing a similar problem in their respective technologies.

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

PHP and mysqli combine to create a versatile image slider with changing images

I am looking to implement an image slider that can be updated by the admin using php and mysqli. The admin should have the ability to easily add or remove images as needed. ...

Running the gulp uncss command with regex to ignore specific elements is not functioning as expected

I have been attempting to integrate uncss into my gulp workflow. In order to exclude certain classes, such as those added through javascript, I am specifying these classes with "ignore" (specifically, I am trying to remove the css from the jquery plugin m ...

Guide to adjusting the number of bounces using jQuery's User Interface (UI)

Check out my code on CodePen: http://codepen.io/Chiz/pen/jbwPLO (click anywhere in the blank area) I'm trying to figure out how to adjust the number of bounces a div makes before stopping. For example, I want the div to bounce 10 times and also chang ...

Tabcontainer in ajax not displaying tabs correctly in Internet Explorer 8

Currently, I am utilizing an AJAX tab container inside an update panel (along with a ToolScriptManager placed in the master pages) to display two tab controls. Interestingly, the tabs are rendering without any issues in Firefox, however, they are throwing ...

Loading a div when the page loads

Is there a way to load an action automatically when the page loads? I'm currently working with struts2 and jquery. I need to retrieve all the comments related to a specific element called commentOn. To achieve this, I am sending the value of commen ...

What is causing the z-index to not function properly on my elements?

In my current code setup, I have positioned the hero image at the bottom with an overlay on top that contains text and a button. Additionally, there is a navigation bar with a z-index applied. However, I am facing an issue where the button for viewing my r ...

Strategies for rearranging columns within Bootstrap 4

I'm new to working with bootstrap and I've been struggling to change the order of columns when viewed on mobile devices. Here's what I've attempted so far: <div class="container"> <div class="row"> & ...

Update the text on the Bootstrap modal label before it is clicked

I am currently working on implementing a Bootstrap modal with a label control. The modal is triggered by clicking a button, and I am facing an issue where I need to change the text of the label before the modal launches. However, the text that is supposed ...

Error encountered when attempting an ajax call across different origins

function fetchInfo() { var endpointUrl = "https://api-oauth2.mendeley.com/oauth/authorize?client_id=374&redirect_uri=https://localhost/api/mendeley/mendeley.php&response_type=code&scope=all&JSON=1"; $.ajax({ url: endpointUr ...

Is there a way to resolve the issue of this div sticking to the top of the

I am currently working on building a portfolio website. One issue I'm facing is that my first div (for the "About Me" section) appears below my second div on the webpage. My goal is to have the first div displayed in full screen on both mobile and des ...

Updating the correct list item in an unordered list on a Bootstrap modal pop-up submission

I am dealing with an unordered list of messages where each message within a list item is clickable. <ul id="home-message-list" class="messages"> <li> <a href="#"> <span class="linkClick" name="message">< ...

Choose the immediate sibling located right after a specific element

My goal is to have the second paragraph following a h1 element display a dropcap, with the first being reserved for the author and date. Although I've tried using different CSS combinations like h1 + p::first-letter {}, it only affects the first para ...

Obtain the response from the aspx page in JSON format instead of the standard HTML

Is it possible to make an ajax call to the server and fetch the HTML of a specific page, like foo.aspx? Here is an example of the HTML code for foo.aspx: <form> <div>foo</div> </form> If I were to call this page from a remote loca ...

Column Flow in CSS Grid: Maximizing Auto-Fit - How to Optimize Row Layouts?

Having some trouble understanding how auto-fill and fit work in grid layouts. I am familiar with basic CSS, but new to working with grid layouts. I have a set of checkbox items with labels that I want to display in columns depending on screen size, with c ...

Displaying a profile hover card allows users to easily discover and choose whether to follow or explore

I created a profile hover card on my website with a follow/unfollow button. However, I encountered an issue - the hover card disappears when I move away from my profile thumbnail. How can I fix this so that the hover card stays visible on mouseover and dis ...

Implementing AJAX in Zend framework

I am interested in incorporating ajax functionality into the Zend Framework. Can you please provide me with a straightforward example? ...

Implementing an ajax search functionality

I am currently working on implementing an AJAX search feature into my project. The application initially displays all client data in a table on the webpage. When something is typed into the search bar, I want the search results to be shown instead of all ...

My goal is to create text that is opaque against a backdrop of transparency

Is it feasible using CSS to create text with a transparent background while keeping the text opaque? I attempted the following method: p { position: absolute; background-color: blue; filter: alpha(opacity=60); opacity: 0.6; } span { color: b ...

What's the Hold-Up with IntersectionObserver in Brackets?

As a novice in the world of web development, I have been utilizing Brackets as my main tool. Recently, I've encountered a few hurdles specifically related to javascript. One issue I'm facing is trying to implement lazy loading on a div containing ...

Transfer a form's file and text data to PHP with the help of jQuery and AJAX

Hey there! I'm currently working on enhancing the user experience for submitting messages by avoiding page reloads. The challenge I'm facing is that the message could consist of either text or an image, and I need to upload both to a PHP page. He ...