What is the best way to choose CSS class attributes using Mootools and the getStyle()

Seeking to duplicate an object, I am trying to figure out how to retrieve class CSS attributes from Mootools.

css:

.card {
width: 109px;
height: 145px;
}

html:

<div id="cards">
    <div class="card" id="c0">
        <div class="face front"></div>
        <div class="face back"></div>
    </div>
</div>

js:

window.addEvent('domready', function(){
 Duplicacartes();
});
function Duplicacartes(){
 var uiCards= document.getElementById('cards');
 for(var i=1;i<521;i++)
{
        var clone = $('c0').clone();
        clone.set('id', 'c'+i);
        clone.setStyle('left', (clone.getStyle('width') + 20) * (i % 40));
        clone.setStyle('top', (clone.getStyle('height')  + 20) * Math.floor(i / 40));
        clone.inject('cards','bottom');

}

However, I am not getting the desired outcome:

The function clone.getStyle() only retrieves the 'element' attributes, not the class CSS attributes. I have tried numerous methods without success.

$('c'+i).getStyle('width'); 
$('c'+i).style.width;
...

Can anyone advise on the correct approach? Thank you.

Answer №1

It may not be possible to retrieve that information from the cloned element directly, but you can copy it from the original element and utilize .getComputedSize() method like so:

var computed = $('c0').getComputedSize();

Your function can be structured this way:

window.addEvent('domready', function () {
    Duplicacartes();
});
function Duplicacartes() {
    var uiCards = document.getElementById('cards');
    var computed = $('c0').getComputedSize();
    for (var i = 1; i < 521; i++) {
        var clone = $('c0').clone();
        clone.set('id', 'c' + i);
        clone.setStyle('left', (computed.width + 20) * (i % 40));
        clone.setStyle('top', (computed.height + 20) * Math.floor(i / 40));
        clone.inject('cards', 'bottom');

    }
}

Fiddle

Note:
- I have also included position:absolute; in the css.
- Remember that .getComputedSize() belongs to More, so make sure to load More as well.

Answer №2

Method: Retrieve Element Style

GetStyle() function is used to fetch the CSS property of an element and returns it as a string (for example, returning "300px" for width). However, this can lead to incorrect mathematical calculations resulting in a NaN (Not-a-Number) value, causing issues with setting the left and top CSS styles through MooTools.

To resolve this, it is recommended to convert the width and height properties to integers using the toInt() method:

clone.getStyle('width').toInt()

When dealing with a large number of elements, script optimization is necessary. One approach is to avoid storing references to cloned elements unnecessarily, and it is sufficient to find the element to be cloned only once.

window.addEvent('domready', function(){;
    Duplicacartes();
});

function Duplicacartes() {
    var card = $('c0');
    for ( var i=1; i<521; i++ ) {
        card.clone().set({
            id: 'c'+i,
            styles: {
                left:   (card.getStyle('width').toInt() + 20) * (i % 40),
                top:    (card.getStyle('height').toInt() + 20) * Math.floor(i / 40)
            }
        }).inject( 'cards', 'bottom' );
    }   
}

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

Exploring sagas: Faking a response using a call effect

In my current scenario, I am facing a challenging situation: export function* getPosts() { try { const response = yield call(apiCall); yield put({ type: "API_CALL_SUCCESS", response }); } catch(e) { // ... } Furthermore, there is a spec ...

Retrieve data from a specific page on a URL using AJAX

window.onload= function(){ var page = window.location.hash; if(window.location.hash != ""){ page = page.replace('#page:', ''); getdata('src/'.page); } } Once the window has loaded, I want to check ...

JavaScript Simplified Data Sorting after Reduction

I have extracted data from a JSON file and successfully condensed it to show the number of occurrences. Now, my next step is to arrange these occurrences in descending order, starting with the most frequent. To illustrate: var myData = [{ "datapo ...

Why isn't the jQuery click() function functioning on my modified HTML?

I am trying to create a unique version of the go-moku game using different programming languages and databases. My aim is to enhance the game's functionality by incorporating jQuery, PHP, and a MySQL database. var moveCount = -1; setInterval(function ...

Node.js: Calculating the number of requests processed per second in the http.get()

In my node.js project, I am creating a simple application for sending HTTP requests. var http = require('http'); var options = { host: 'www.example.com', port: 80, path: '/index.html' }; for(var i = 0; i < 500; i++ ...

Creating a WebExtension using Angular and TypeScript

I am currently working on creating a WebExtension using Angular and Ionic. The extension successfully loads the application and enables communication between Content Script and Background Script. However, I am facing an issue where the TypeScript code is n ...

In the realm of asp.net, the OnClick event springs into action after the

My asp button uses OnClientClick to execute a javascript function, and I also want to run OnClick after OnClientClick. However, the OnClick never seems to execute. Despite looking through similar topics on StackOverflow and other websites, I can't see ...

Use vtip jQuery for showcasing titles

Currently, I am utilizing the vTip plugin for displaying titles upon hover. Here is a snippet of my code: http://jsfiddle.net/bnjSs/ In my HTML, there's a Div with the ID #showTitles. Whenever this Div is clicked, I aim to toggle the display of all ...

Encountering issues with styling the search bar using CSS and unable to see any changes reflected

I am currently working on creating a searchBar and customizing its CSS, but unfortunately, most of the styling properties seem to not be taking effect. So far, only changing colors seems to work as expected. .mainBar{ background-color: blue; width: ...

Assign a CSS class to a DIV depending on the vertical position of the cursor

The website I am currently developing is located at Within the site, there is a collection of project titles. When hovering over a project title, the featured image is displayed directly below it. I would like to change the positioning of these images to ...

Adjust the node_modules path tailored to your project

My current project structure looks like this: |-app |-... |-libs |- package.json |- index.html I am interested in organizing my project such that the 'node_modules' folder is inside the 'libs' folder. The desired structure is as fo ...

The React engine is triggering an error stating "Module not found."

Utilizing react-engine to enable the server with react component access. Through react-engine, you can provide an express react by directing a URL and utilizing res.render. The documentation specifies that you need to supply a path through req.url. app.use ...

What is the ternary operation syntax for setting the img src attribute in Angular 8?

My data includes a property called "photo" which can either have a file name or be empty. For instance, it could be "steve.jpg" or just an empty string if Steve does not have a photo. In React JSX, I know how to use a ternary operator with the "photo" va ...

Guide to setting up a horizontal button menu and dropdown submenu beneath the navigation bar using Bootstrap 4

How can I design a horizontal button menu with submenus below the navigation bar in Bootstrap 4? Take a look at the image below to see what I'm aiming for: https://i.sstatic.net/j6b8a.png https://i.sstatic.net/rmtrM.png If you have any ideas or su ...

Is there a way to adjust this validation logic so that it permits the entry of both regular characters and certain special characters?

Currently, the input field only accepts characters. If any other type of character is entered, an error will be thrown as shown in the code below. How can I update this logic to allow not only letters but also special characters like hyphens and apostrop ...

Basic Timer with Visual Background

Struggling to find the right CSS/script for a straightforward countdown timer, Here are the requirements: Countdown in days only, no need for hours, minutes, and seconds Ability to use a custom image as background I've scoured online searches but n ...

What is the most effective way to implement multiple ng-models within a single function?

Hello everyone! Currently, I am working on developing a database using indexed db in AngularJS. My main task is to save data into the database and I have a query - Can we utilize multiple ng-models in a single function? Let me provide you with a snippet of ...

Choose the DIV element based on its data attribute using JSON

When using each(), my goal is to: Hide all divs where the data-infos.grpid = $jQuery(this).data('infos').grpid Show the next div where data-infos.ordre = $jQuery(this).data('infos').next_ordre I am unsure how to apply a "where" ...

Whenever I create the code using javascript, padding seems to always show up

I have a basic stacked row layout that displays an upper box and lower box without any padding. <span id="route" class="small"> <div class="row" style="border-style:solid;"> <div class="col-md-12 col-12"> <p>UpperBox</p& ...

Tips for Deploying Your NuxtJS Project on a Shared Hosting Service

After creating my NuxtJS project locally, I am now facing the challenge of deploying it to a shared hosting provider like Host Gator. Since I intend to utilize the server side rendering feature of NuxtJS, I know I need to execute the following command: n ...