What is a suitable CSS attribute/value combination to act as a trigger for JavaScript functionality?

I am in search of a unique way to move a DOM Object within another one on specific screen sizes. The idea stemmed from this insightful answer. While fixed widths are an option, my layout is flexible with LESS, so I aim to avoid using them as triggers. This lightweight method does not require additional libraries like require.js or modernizr to emulate media queries, making it ideal for my needs.

Currently, I am utilizing a bottom margin of 1px, but I find it unsatisfactory. I am on the lookout for an unconventional and senseless CSS value that can serve as a trigger. "move-to" in CSS3 seems promising, yet it remains a work in progress draft with no browser implementation noted. It does not even register in tools like Firebug.

This is my current approach:

CSS

@media screen and (min-width: 768px) {

    .sidebar-secondary {
        margin-bottom: 1px;
    }

}

@media screen and (min-width: 992px) {

    .sidebar-secondary {
        margin-bottom: 0;
    }

}

Javascript

var sidebar_move = function(){
    if ( $(".sidebar-secondary").css("margin-bottom") === "1px") {
        $(".sidebar-secondary").appendTo(".sidebar-primary");
    }
}

window.setInterval(sidebar_move, 1000);

Any suggestions for a "nonsensical" CSS value I could utilize? Something obscure that people typically do not use. Ideally, it should be conflict-free and impervious to changes made by others, making margin a less than optimal solution.

Many advocate adding JavaScript code to enhance functionality, however, I am interested in understanding the rationale behind this viewpoint.

Additionally, I believe this method is more dependable than extracting window width through JavaScript, which explains the existence of complex scripts like equire.js. Or perhaps my understanding is flawed?

Is there a downside to linking JavaScript functions to CSS parameters? I intend to apply this concept solely for this purpose and nothing else.

Answer №1

Consider implementing Enquire.js for a more efficient solution that avoids unnecessary CSS rules.

The code example using Enquire.js would be:

enquire.register("screen and (min-width:768px)", {

    match : function() { 
        $(".sidebar-secondary").appendTo(".sidebar-primary"); 
    },

    unmatch : function() {
        /* e.g. remove .sidebar-secondary from .sidebar-primary */
    }
}).listen();

This method is preferable to relying on JavaScript tied to specific CSS rules because:

  • Maintenance of the app becomes more difficult if others can inadvertently break functionality by changing a rule;
  • It's best practice to keep CSS separate from JavaScript, and vice versa, instead of closely intertwining them.

Answer №2

I have been implementing a similar approach to what you are doing (even though this discussion is a year old, it does not appear to provide the solution that the OP was looking for, and this happened to be one of the first links that popped up in my own Google search).

/* Custom CSS Styles */
.mediaQueryTracker {
     width:auto;
}

/* Responsive Design for Mobile */
@media only screen and (max-width: 479px) {
     .mediaQueryTracker {
          width:479px;
     }
}

Regarding Javascript:

var mobile_handler = function() {
    if ( $(".mediaQueryTracker").css("width") !== "auto") {
        // Perform actions
    }
}

You can apply this class to an empty div with hidden or none display settings, or alternatively, you can assign the mobileQueryTracker class to your main container or wrapper directly in the HTML code. The value will adjust based on the current media query. You have the flexibility to handle specific tasks for each designated size or target all mobile sizes by verifying that the width is not set to auto.

A simpler approach would be to forego the name "mobileQueryTracker" and utilize the width of your container or wrapper element directly.

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

Deactivate the AJAX button after the specified number of clicks

Imagine I have a model called Post, and it can be associated with up to n Comments (where the number is determined by the backend). Now, let's say I have a view that allows users to add a Comment through an AJAX request. What would be the most effecti ...

Modify the div's width from 100% to 1000 pixels when it is less than 1000 pixels, using Javascript

I need help with writing Javascript code that will change the width of a div element called "red" from 100% to 1000px when the browser width is less than 1000px. The code should revert the width back to 100% when the browser width is greater than 1000px. ...

Arranging ul tags in divs horizontally side by side

I am attempting to create a <div> that contains several <ul> lists, but I seem to be having trouble getting it to work correctly. In essence, I'm trying to achieve something similar to this: https://i.sstatic.net/ZIADB.png This is my cod ...

What is the best way to delete these <li> tags according to their respective timestamps?

When the page loads, there are initially 5 <li> elements. Additional <li> elements are then randomly added every few seconds. I want to remove any <li> elements that have been on the page for more than a minute. My plan is to create an ...

Encountered an error when trying to open the bootstrap dropdown within ng-grid/ui

Is there a way to trigger the opening of a bootstrap-dropdown by clicking on a cell within ng-grid? I am currently only able to open it partially. Check out this Plunker link ...

Tips for inserting HTML into elements using Angular

Recently, I delved into Angular and decided to experiment with Ajax by fetching a document to display on my webpage. The process worked flawlessly, but now I face a new challenge: injecting HTML content into a DOM element dynamically. Typically, this task ...

Maximizing spacing for element alignment using space-evenly and :after

I have employed the pseudo-element :after to left-align the last line of a list of blocks, using space-evenly to justify these blocks. However, I am facing an issue where the blocks on the last line do not align properly with the others due to the space ta ...

I'm curious if there is a specific jQuery event that triggers right before an element loses focus or right before the next element gains focus

I am facing a situation where I have two input elements in a form that are closely connected. The first element triggers an ajax call to check for existing data in the database when the user tries to move away from it, while the second element opens a moda ...

`Balance in structure`

Having trouble with CSS. I would like to make this form symmetrical. Buttons should be in one column, textfields in another, and the question mark should also have its own column. Apologies if the ticket structure is not perfect, this is only my second on ...

Guide on Cordova: Playing MP4 videos in fullscreen and endless loop

I am looking to display a specific mp4 video file in fullscreen mode and on loop playback. Is there a plugin available that can help me achieve this? While researching, I came across the Videogular library designed for Angular-based applications. However ...

Tips for implementing a double loop on a JSON result

Here is the JSON result I'm working with: https://i.sstatic.net/ih4CH.jpg I am able to loop through the first level of the JSON data, but I am having trouble looping through the second level (SUBCATEGORIA). <ScrollView> {this.state.item ...

Add a span tag with the class "javascript" around the index of a character within a string

Within an element, I have a string as such: <p>I like trains and planes</p> Using jQuery's .text(), I extract the text and store it in a variable. var str = $('p').text(); I aim to identify a specific character, let's sa ...

Iterating through records with a set of three columns in every row

I need to divide each row into 3 columns image : https://i.sstatic.net/4phtb.jpg <div id="list-product"> <div class="row"> @foreach($products as $product) <div class="col-lg-4 ...

Obtain the value of a checkbox using jQuery

Here is an example of dynamic checkboxes: <input type="checkbox" checked="checked" value="1" name="user_mail_check[]" class="ami"> <input type="checkbox" checked="checked" value="2" name="user_mail_check[]" class="ami"> <input type="checkbo ...

The remove() function successfully removes options from the select box, but the hide() function did

I am trying to create functionality where select box options are shown or hidden based on the input field value. Surprisingly, this only seems to work with $('thisOption') when removing (), but not with: $('thisOption').hide() // or: ...

Troubleshooting Problem with Responsive Bootstrap Navbar

I've been working on creating a menubar using Bootstrap where the logo image is centered instead of being on the left side of the bar. However, I'm facing an issue where the right links in the menu go off the screen. When I view the page with a w ...

Tips on sending non-form values to an action in Struts 1.3 via AJAX

Here is a snippet of JSP code that I am working with: <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%> < ...

The div "tags" cannot be positioned beneath the photo as it is automatically located alongside the image inside the div

Is there a way to place the "Tags" div beneath an image, creating a bar of tags below it? I've been struggling to position it properly without disrupting the flow of the page. Using absolute positioning is not an option as it would break the layout. A ...

Retrieve a specified quantity of JSON data from an external API

Dealing with a recently received API from an external source: (please note: the data returned is extensive) I'm aware that I can retrieve this large object by using the following method: $.getJSON('https://www.saferproducts.gov/RestWebServices ...

Using NodeJS to fetch external page data and return Javascript variable information

I need to retrieve the entire DOM of a specific page by sending a request, essentially crawling the website. The HTML directly includes a variable with some data, instead of it being in a separate script file. With my NodeJS backend, I am utilizing request ...