Javascript function is providing unexpected output

I have a function that should display 4 different flags, but it's not working as expected. There are no error messages, but the flags are not being printed either. I've tried everything I could think of and now I'm stuck. Can someone please help me out?

(function () {
    'use strict';
    function draw() {
        for (var i = 0; i < v.length; i++) flagTarget.init()
    }

    var flagTargetIvoryCoast = document.getElementById('flag-elfenbenskusten');
    var flagTargetSweden = document.getElementById('flag-sverige');
    var flagTargetMauritius = document.getElementById('flag-maruritius');
    var flagTargetJapan = document.getElementById('flag-japan');


    var flagTarget = {
        init: function () {
            if (flagTargetIvoryCoast) {
                var flagIvoryCoast = '<div class="flag ivory-coast"><div class="part1"></div><div class="part2"></div></div>';
                console.log('drawing flag Ivory Coast'),
                flagTargetIvoryCoast.innerHTML = flagIvoryCoast;
            }
            if (flagTargetSweden) {
                var flagSweden = '<div class="flag1 sweden"><div class="box1"></div><div class="box2"></div><div class="box3"></div><div class="box4"></div></div>';
                console.log('drawing flag Sweden'),
                flagTargetSweden.innerHTML = flagSweden;
            }
            if (flagTargetMauritius) {
                var flagMauritius = '<div class="flag2 mauritius"><div class="box1"></div><div class="box2"></div><div class="box3"></div><div class="box4"></div><div class="box5"></div></div>';
                console.log('drawing flag Mauritius'),
                flagTargetMauritius.innerHTML = flagMauritius;
            }
            if (flagTargetJapan) {
                var flagJapan = '<div class="flag3 japan"><div class="box1"></div><div class="cirkel1"></div></div>';
                console.log('drawing flag Japan'),
                flagTargetJapan.innerHTML = flagJapan;
            }
        }
    },

    flagTargetIvoryCoast = Object.create(flagTarget),
    flagTargetSweden = Object.create(flagTarget),
    flagTargetMauritius = Object.create(flagTarget),
    flagTargetJapan = Object.create(flagTarget),

    v = [
        flagTargetIvoryCoast,
        flagTargetSweden,
        flagTargetMauritius,
        flagTargetJapan,
        ];

    draw(),
    console.log('Sandbox is ready!')
}());

My console output shows the flags being drawn multiple times, and I can't figure out why. Any assistance would be greatly appreciated!

Answer №1

You may be facing an issue where you are constantly outputting the result (4 times) within your loop due to the fact that your condition: if (flagTargetElfenbenskusten) will always evaluate to true (resulting in the conditions always being met).

Since you are checking for variables not being null and they are indeed not null (the divs exist in the DOM), you should update your code as follows:

 var flagTargetElfenbenskusten = document.getElementById('flag-elfenbenskusten').textContent; // include textContent to retrieve input values
// repeat the same for the other 4 variables

Your updated code should look like this:

if (flagTargetElfenbenskusten !== null) {
   // place your code here

Additionally, it seems you haven't assigned any IDs to your div elements, so your final code should appear as follows:

EDIT 2:

(function () {
'use strict';
function draw() {
    for (var draw = 0; draw < v.length; draw++) flagTarget.init()
}

var flagTargetElfenbenskusten = document.getElementById('flag-elfenbenskusten').textContent;
var flagTargetSverige = document.getElementById('flag-sverige').textContent;
var flagTargetMaruritius = document.getElementById('flag-maruritius').textContent;
var flagTargetJapan = document.getElementById('flag-japan').textContent;

var flagTarget = {
    init: function () {
        if (flagTargetElfenbenskusten !== null) {
            var flagElfenbenskusten = '<div id="flag-elfenbenskusten" class="flag elfenbenskusten"><div class="part1"></div><div class="part2"></div></div>';
            console.log('drawing flag elfenbenskusten'),
            flagTargetElfenbenskusten.innerHTML = flagElfenbenskusten;
        }
        if (flagTargetSverige !== null) {
            var flagSverige = '<div id="flag-sverige" class="flagga1 sverige"><div class="box1"></div><div class="box2"></div><div class="box3"></div><div class="box4"></div></div>';
            console.log('drawing flag Sverige'),
            flagTargetSverige.innerHTML = flagSverige;
        }
        if (flagTargetMaruritius !== null) {
            var flagMaruritius = '<div id="flag-maruritius" class="flagga2 maruritius"><div class="box1"></div><div class="box2"></div><div class="box3"></div><div class="box4"></div><div class="box5"></div></div>';
            console.log('drawing flag Maruritius'),
            flagTargetMaruritius.innerHTML = flagMaruritius;
        }
        if (flagTargetJapan !== null) {
            var flagJapan = '<div id="flag-japan" class="flagga3 japan"><div class="box1"></div><div class="cirkel1"></div></div>';
            console.log('drawing flag japan'),
            flagTargetJapan.innerHTML = flagJapan;
        }
    }
},

flagTargetElfenbenskusten = Object.create(flagTarget),
flagTargetSverige = Object.create(flagTarget),
flagTargetMaruritius = Object.create(flagTarget),
flagTargetJapan = Object.create(flagTarget),

v = [
    flagTargetElfenbenskusten,
    flagTargetSverige,
    flagTargetMaruritius,
    flagTargetJapan,
    ];

draw(),
console.log('Sandbox is ready!')
}());

You were using getElementById() without specifying any corresponding IDs.

The for loop inside your function is unnecessary, modify it as shown below:

function draw() {
    flagTarget.init()
}

EDIT 3:

Remember to call the init method on page load to generate the flag divs:

window.addEventListener("load", flagTarget.init());

Answer №2

  • within the render method, you invoke the initialize function 4 times
  • all four conditions are met within the initialize function

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

JavaScript Code to Remove an Element from an Array

I have a Javascript Filter Item Class and an array structured as follows: function FilterItem(filterId, filterType) { this.filterId = filterId; this.filterType = filterType; } var filterItemArray = []; To add Filter Items to this array, I use th ...

Utilizing AngularJS to make an API call with $http method and handling a

I am attempting to make a call to my webservice using "$http". When I use "$ajax", it works fine. Here is an example of jQuery $Ajax working correctly: $.ajax({ type: "Get", crossDomain: true, contentType: "application/json; chars ...

Receiving an error while trying to install packages from the NPM registry due to non

I am facing some challenges while attempting to install my Ionic App through the registry along with its dependencies. I have been using npm i --loglevel verbose command, and my ~/.npmrc file is configured as follows: //nexus.OMMITED.com/repository/:_auth ...

Javascript - parsing a string to create a mathematical equation

Suppose I have an image URL structured like this: blabla.com/bla/twofive.hash.png This type of URL can be converted into a JavaScript string. I am interested in learning how to create an array that breaks down the URL based on special characters, such a ...

Styling an exponential number in a table header using Vuetify

I am looking to replace the default header 'number' with a custom HTML header while using vuetify for displaying a data table. My current setup looks like this: headers: [ {text: 'number', value: &a ...

React: Component styles fail to update dynamically

I have been working on creating a component that can adjust its size dynamically based on props. Currently, I am experimenting with the code below, but I've noticed that when I change the slider, the component's size doesn't actually change. ...

Tips for extracting data from a website that dynamically updates its content as the user scrolls

This is a link that I am trying to extract data from. The website alters its product display after scrolling to the 8th element. It seems like there are over 200 products listed after a search query, but only 8 are visible in the page source. When scroll ...

Is transforming lengthy code into a function the way to go?

I have successfully implemented this code on my page without any errors, but I am wondering if there is a more concise way to achieve the same result. Currently, there is a lot of repeated code with only minor changes in class names. Is it possible to sh ...

Is it possible to assign a deconstructed array to a variable and then further deconstruct it?

Is there a way to deconstruct an array, assign it to a variable, and then pass the value to another deconstructed variable all in one line of code? Take a look at what I want to achieve below: const { prop } = [a] = chips.filter(x => x.id == 1); Typic ...

Creating an app using Ionic 1 that features scrollable tabs with the ability to handle overflow

My current code snippet is displayed below. On smaller mobile screens, all 7 tabs are not visible at once and instead appear in two rows which looks messy. I want to modify the display so that only 3 tabs are visible at a time and can be scrolled through. ...

What mechanisms do frameworks use to update the Document Object Model (DOM) without relying on a

After delving into the intricate workings of React's virtual DOM, I have come to comprehend a few key points: The virtual DOM maintains an in-memory representation of the actual DOM at all times When changes occur within the application or compo ...

Creating a Future Prediction Graph with ECharts

I am looking to create a forecast chart that includes both Actual values (presented as a line chart) and projected values (displayed as a dotted chart). An example of what I have in mind can be seen here, created using Excel: https://i.sstatic.net/q18An.pn ...

The error message "Node.js is throwing a next() error that is not a

var express = require('express'); var app = express(); var middleware = { requireAuthentication: function(req, res, next){ console.log("private route hit"); next(); } }; app.use(middleware.requireAuthentication()); app ...

A method for modifying the key within a nested array object and then outputting the updated array object

Suppose I have an array called arr1 and an object named arr2 containing a nested array called config. If the key in the object from arr1 matches with an id within the nested config and further within the questions array, then replace that key (in the arr1 ...

Switching out text when hovering with Jquery or JavaScript

Is there a way to use jQuery or JS to make the text and icon disappear when hovering over a div, and replace it with "Read More"? I've looked at some guides but they only remove one line of text instead of clearing the entire div and displaying "Read ...

Unable to fetch a new session from the selenium server due to an error

I'm currently in the process of setting up Nightwatch.js for the very first time. I am following the tutorial provided at this link: https://github.com/dwyl/learn-nightwatch Unfortunately, I have encountered a barrier and require assistance to resolv ...

What is the correct way to show a JavaScript response on the screen?

Here is the JavaScript code I used to call the server API: <script type='text/javascript'> call_juvlon_api(apikey, 'getAvailableCredits', '', function(response) { document.getElementById('show').innerHT ...

Tips for ensuring a successful POST request using a hyperlink tag

Within my view file, I have the following code snippet: <a href="/logout" role="button" class="btn btn-lg btn-primary left-button">Logout</a> Inside my app.js file, I have implemented the following route for loggi ...

The abort() function in Chrome can trigger an Undefined Error

When dealing with race conditions, I implement the following code to throttle get requests: if (currentAjaxRequest !== null) { currentAjaxRequest.abort(); } var query_string = getQuery(); currentAjaxRequest = ...

Tips for sending a MySQL parameter

Hey there, I need some help with the trigger setup I have: CREATE TRIGGER `update` AFTER UPDATE ON `table 1` FOR EACH ROW INSERT INTO table 2 ( Id, Revision, Purpose, Change ) VALUES ( OLD.Id, OLD.Revision, OLD.Purpose, @purpose_change /* user variable ...