Dynamically incorporating a new carousel element using JavaScript within Onsen UI 2

Attempting to dynamically add a new carousel item using JavaScript in Onsen UI 2, but encountering an issue. Below is the code being used:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="node_modules/onsenui/css/onsenui.css"/>
        <link rel="stylesheet" href="node_modules/onsenui/css/onsen-css-components.css"/>
        <script src="node_modules/onsenui/js/onsenui.js"></script>
        <script src="jquery.js"></script>
    </head>

    <body>
        <ons-splitter>
            <ons-splitter-side id="menu" side="left" width="220px" collapse swipeable>
                <ons-page>
                    <ons-list>
                        <ons-list-item onclick="fn.load('home.html')" tappable>
                            Home
                        </ons-list-item>
                    </ons-list>
                </ons-page>
            </ons-splitter-side>
            <ons-splitter-content id="content" page="home.html"></ons-splitter-cont

ent>
            <ons-navigator id="myNavigator" page="home.html"></ons-navigator>
        </ons-splitter>

        <ons-template id="home.html">
            <ons-page id="home">
                <ons-toolbar>
                    <div class="left">
                        <ons-toolbar-button onclick="fn.open()">
                            <ons-icon icon="ion-navicon, material:md-menu" size="32px, material:24px"></ons-icon>
                        </ons-toolbar-button>
                    </div>
                    <div class="center top-bar-title"></div>
                    <div class="right">                 
                        <ons-toolbar-button id="addInCarousel">
                            <ons-icon icon="ion-ios-plus, material:md-plus" size="32px, material:24px"></ons-icon>
                        </ons-toolbar-button>
                    </div>
                </ons-toolbar>

                <ons-carousel auto-refresh fullscreen swipeable auto-scroll overscrollable id="itemsCarousel" direction="horizontal">
                    <ons-carousel-item>
                        <img src="images/01.jpg" style="width: 100%; height: auto;"/>                   
                    </ons-carousel-item>                
                    <ons-carousel-item id="caro2">
                        <img src="images/02.jpg" style="width: 100%; height: auto;"/>
                    </ons-carousel-item>                
                </ons-carousel>
            </ons-page>
        </ons-template>

        <script>
            window.fn = {};
            window.fn.open = function() {
                var menu = document.getElementById('menu');
                menu.open();
            };

            window.fn.load = function(page) {
                var content = document.getElementById('content');
                var menu = document.getElementById('menu');
                // content.load(page).then(menu.close.bind(menu));
                document.querySelector('#myNavigator').pushPage(page);
                menu.close();
            };  

            ons.ready(function() {
                var carousel = document.addEventListener('postchange', function(event) {
                    console.log('Changed to ' + event.activeIndex);
                });     
            });

            document.addEventListener("init",function(event) {
                var page = event.target;

                if( page.matches('#home') ) {
                    // set page header title
                    page.querySelector('ons-toolbar .center').innerHTML = 'Testing App';

                    // clicking on header add button for adding new carousel item
                    page.querySelector('#addInCarousel').onclick = function() {
                        console.log("In function");
                        var onsItem= document.createElement('ons-carousel-item');                       
                        onsItem.innerHTML = '<img src="images/020.jpg" style="width: 100%; height: auto;"/>';               
                        document.getElementById('itemsCarousel').appendChild(onsItem);
                    };          
                }
            }, false);
        </script>
    </body>
</html>

The code that aims to add a new carousel item is provided below:

// clicking on header add button for adding new carousel item
                    page.querySelector('#addInCarousel').onclick = function() {
                        console.log("In function");
                        var onsItem= document.createElement('ons-carousel-item');                       
                        onsItem.innerHTML = '<img src="images/020.jpg" style="width: 100%; height: auto;"/>';               
                        document.getElementById('itemsCarousel').appendChild(onsItem);
                    }; 

Please assist in identifying any errors. Any references or samples would be highly appreciated.

Answer №1

To ensure proper initialization of the home.html pages, you can nest your <ons-navigator> within the <ons-splitter-content> and remove the page attribute from the <ons-splitter-content>.

<ons-splitter-content id="content">
    <ons-navigator id="myNavigator"></ons-navigator>       
</ons-splitter-content>

Additionally, it is recommended to replace the use of document.getElementById("id") in your function with page.querySelector("#id"), as the latter method specifically looks for the id on the current page.

Therefore, your modified function should resemble the following:

page.querySelector('#addInCarousel').onclick = function() {
     console.log("Inside the function");
     var onsItem= document.createElement('ons-carousel-item');                       
     onsItem.innerHTML = '<img src="images/020.jpg" style="width: 100%; height: auto;"/>';               
     page.querySelector('#itemsCarousel').appendChild(onsItem);
}; 

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

Leveraging the power of the JQuery on and off function to add and delete specific event listeners

In my current code, I am utilizing the JQuery on method to link an event handler to the window object: $(window).on('resize', function(e){ /** my functional code goes here **/ e.stopPropagation(); }); The issue I am facing is that this ...

Is there a way to obtain the Base64 data following the conversion of a div to an image?

I am not very experienced with JavaScript, but I wanted to convert a div to an image. I came across this helpful jsfiddle that showed me how to do it. $(function() { $("#btnSave").click(function() { html2canvas($("#widget"), { on ...

Is it unwise to rely on Sequelize for validating objects that are not stored in a database?

Currently, I am utilizing Sequelize as my ORM and find the powerful built-in model validation to be quite impressive. I am contemplating leveraging Sequelize as a schema validator in specific scenarios where there would not be any actual database writes. E ...

Using Selenium 2 to dynamically insert CSS styles into the currently visible webpage

I experimented with using jQuery on a webpage that has already been modified by jQuery in order to add custom CSS code: jQuery('head').append('<style type=\"text/css\">body { background: #000; }</style>'); When I ...

Displaying geoJSON data from a variable instead of a file is a feature implemented by

Let's say I have a geoJSON data stored in a variable or parsed as an object: // GeoJSON stored as an object var segment = segment; // GeoJSON saved as a JSON string var json = JSON.stringify(segment); Now, the challenge is to display this geoJSON o ...

Steps for assigning an id to an element using Selenium

When using Selenium, you have the ability to access the underlying DOM of the browser being manipulated through IWebElement instances. For example: IWebElement domWrapper = driver.FindElement(By.Name("q")); But what if you have the "domWrapper" instance ...

When using res.json(), the data is returned as res.data. However, trying to access the _id property within it will result

I'm facing a challenge in comprehending why when I make a res.json call in my application, it successfully sends data (an order object). However, when I attempt to access and assign a specific piece of that data (res.data._id) into a variable, it retu ...

Manipulating data rows in a table using jquery

I have a button called #add that, when clicked, adds a new row to a table. The last cell of the newly inserted row contains a delete icon that, when clicked, should remove the entire row. I thought I had everything set up correctly, but for some reason, c ...

What is the method for retrieving the name of the 'Autocomplete' component in Material UI?

Currently, I am faced with the challenge of working on multiple Autocomplete MUI components and am in the process of creating a "generic" event handler that will utilize the useReducer hook to manage the state. The issue lies in the fact that the onChange ...

Utilizing Angular to Transform an Array of Dates

I have an array of dates which returns: [Mon Aug 03 2020 00:00:00 GMT+0100 (British Summer Time), Wed Aug 05 2020 00:00:00 GMT+0100 (British Summer Time)] I am looking to convert these into the following format: ["2020-02-13T02:39:51.054", &quo ...

What is the best way to organize products based on the proximity of users using MongoDB's Geospatial Queries

I'm currently working on a web application that connects users with neighbors to buy and sell products. The app is built using node.js, JavaScript, mongodb, and mongoose. My main issue lies in sorting the products. I want to display products from nea ...

The ng-options loop in the array is unable to locate the specified value

In my C# controller, I generate a list and translate it to Json for Angular to receive at the front end. However, when using ng-options to loop through this array in order to get the array value, I always end up with the index instead. <select class="s ...

Exploring collapsible data tables in Angular with Bootstrap styling

I am attempting to transform my static bootstrap data table, which displays the total count of fruits harvested in various months in an incremental manner, into a dynamic one using the JSON provided below: JSON { "fruit": [ { "fruitName": "Al ...

Using Angular's ng-repeat prefilter with JavaScript

Is it possible to achieve the functionality of this angular js filter ng-repeat on a tr element using pure javascript? Could it be done in just one custom filter? Please note that showRow is a function that returns a boolean value, and searchString is a s ...

Trouble with setting up custom static route

Greetings! I am currently working on setting up my project in React and here is my current project structure: -public --w ---dist ----bundle.js ---index.html -server --server.js -src --app.js -webpack.config.js -package.json -.babelrc For my server, I am ...

A new sub-schema has been created in the JSON schema specifically tailored to a certain property

I needed to create a JSON schema with 3 fields: num, key1, and key2. The fields num and key1 are required, while the field key2 is only mandatory if key1 has a value of 'abc'. Below is the schema structure I came up with: schema = { type: &ap ...

Utilizing JavaScript to enable HTML checkbox to be checked automatically

I am currently working on a constructor that generates checkboxes within a loop. My issue lies in attempting to set these checkboxes as checked, however, it doesn't seem to be functioning correctly. Below is the code snippet: funct ...

Unleashing the power of dynamic column width in Material UI Grid

Is it possible to dynamically change the column width for grid items within the same container in material UI grid? Sometimes I have 2 grid items that need to display in the same row, and other times I have 4 grid items that I want to appear in the same r ...

Using an Ajax call to show a date picker when a button is clicked

I've created buttons for each ID in the "habitaciones" table. When a button is clicked, it should display a specific datepicker with dates disabled for that ID. To achieve this, I utilized an Ajax function where the form should be displayed based on ...

Syncing data between parent and child components in VueJS using v-bind:sync with an object parameter for bidirectional data flow

In the app I am developing, there is a main component that passes an Object, specifically this.form, to a child form component using v-bind:sync="form". The child form then emits values for each key of the parent object on @input events. My goal is to be ...