How to Develop a User Score Function in Javascript Quiz

I am currently trying to build a user score function for a javascript quiz and I can’t seem to figure out how to 1) pull the answer selected based on a click event and 2) determine whether that scrore is true or false. Based on their answer, I want it to build it into a score board. And then post the results at the end of the quiz.

I’ve tried adding a target but can’t seem to even get that to log. I have a check answer function where it moves to the next question but I also want that click event to tally up a score.

Code:

var startQuizBtn = document.getElementById("start-quiz");

// start quiz button with a fuction to trigger the quiz questions (showQuestons())
startQuizBtn.onclick = function() {
  console.log('button click')
  showQuestions(), setTime();
};

console.log(setTime);

var timeEl = document.querySelector(".time");

var resultsEl = document.getElementById("results");

var secondsLeft = 15;
// function that starts timer when you click start quiz
function setTime() {
  // Sets interval in variable
  var timerInterval = setInterval(function() {
    secondsLeft--;
    timeEl.textContent = secondsLeft;

    if (secondsLeft === 0) {
      // Stops execution of action at set interval
      clearInterval(timerInterval);
      // Calls function to create and append results of quiz
      userScore();
    }

  }, 1000);
}


// the questions that will be asked during the quiz 
var myQuestions = [{
    question: "Javascript is an _______ language?",
    answers: ["Object-Oriented", "Object-Based", "Procedural", "None of the above"],
  },
  {
    question: "Which of the following keywords is used to define a variable in Javascript?",
    answers: ["var", "bar", "jar", "bob"],
  },
  {
    question: "Which of the following methods is used to access HTML elements using Javascript?",
    answers: ["targetElement", "thatOneElement", "getElementById", "idElement"],
  },
];

var questionIndex = 0

console.log(myQuestions[questionIndex])
console.log(myQuestions[questionIndex].question)

// main function to show quiz question in a sequential order after clicking start quiz 
function showQuestions() {

  startQuizBtn.style.display = "none";

  var quizAnswers = document.getElementById("answers");

  var questionTitle = myQuestions[questionIndex].question

  var questionh3 = document.getElementById("questions")

  questionh3.textContent = questionTitle
  quizAnswers.textContent = ""

  myQuestions[questionIndex].answers.forEach(function(q) {

    // takes answers and turns them into buttons below questions
    var ul = document.getElementById("answers");
    var li = document.createElement("li");
    var answerBtn = document.createElement("button");
    li.appendChild(answerBtn);
    ul.appendChild(li)
    // button styling
    answerBtn.textContent = q
    answerBtn.style.padding = "10px"
    li.style.listStyle = "none"
    li.style.marginTop = "5px"
    li.style.marginBottom = "5px"


    quizAnswers.appendChild(answerBtn)

    answerBtn.addEventListener("click", checkAnswer)
    answerBtn.addEventListener("click", userScore)

    console.log(q)
  })
}

var scoreCounter = 0;
var answerIndex = 0;

function userScore(e) {

  var selectedAnswer =
    console.log(selectedAnswer)

  var correct = myQuestions.answers
  if (selectedAnswer === correct) {
    scoreCounter = scoreCounter + 1;
  }
}

function checkAnswer() {
  questionIndex++
  showQuestions()
}
<div class="wrapper">
  <header>
    <h1>Code Quiz Challenge</h1>
    <p id="quiz-rules">Welcome to the Javascript fundamentals quiz! Answer the questions to test your Javascript knowledge. This quiz does have a time limit. If you answer the question incorrectly, you will be penalized with ten seconds off your timer. To begin the quiz,
      select Start Quiz below. </p>
  </header>
  <div id=quiz-container>
    <div id="start-button-container">
      <button id="start-quiz">Start Quiz</button>
    </div>
    <h2 class="time">
      </h1>
      <h3 id="questions"></h3>
      <ul id="answers"></ul>
      <div id="score"></div>
  </div>

Node.js modules and recursion

I have created a node.js module which contains method a with optional recursive calls. Simplified structure:

module.exports = {
a() {
 // ...
 if (condition) {
  a();
  b();
 }
 // ...
}

 b() {
  //...
 }
}

After importing this module with const { a } = require(path) calling a with arguments that cause condition to be false works perfectly.
However, when a is called recursively, a ReferenceError is raised with message “a is not defined”.

Changing the recursive call to this.a() seems to fix the original problem, however now the same error is being raised for b, with and without this in front of it.

How can I fix this?

is there a way to make a get request with token and data with both axios and fetch?

I have learnt that http get requests not meant to accept data as part of what it is sending, and I equally tried this with fetch and axios multiple times trying to perform a get request with body (i.e data) and token, it didn’t work

await axios.get(
    'https://dev.app.payslice.com/api/account_info', 
    {bank_code: bank?.code, account_number}, 
    {headers: {"Authorization": `Bearer ${token}`},
}).then(res => console.log(res))

this is what is in the docs, but despite this, it was returning unauthorized in the network tab, but after trying to remove the data, and trying the request again it showed authorized but data not passed, (i.e some fields were required).

Any comments would be appreciated

k6 – Do functions wait for async methods to finish?

So I have a bit of a question, that relates both to k6 and to I guess JavaScript itself. (Also I realize k6 is built upon Go language but uses JS).

Anyways in K6 you have a default function that looks like this:

export default function () {
  http.get('https://test.k6.io');
  sleep(1);
}

In my scenario I need to wait 400ms between two different HTTP requests. K6 has an experimental setTimeout function that does this. So I simply did the below:

export default () => {
http.patch(firstURL,body,params)
setTimeout(() => {
  const res = http.post(secondURL,body,params)
  console.log(res.status)
}, "400");
}

So this did indeed work. It appeared to wait 400ms before executing the second request. However my question is: While it’s waiting for that 400ms to end, does the main default function “end”?

As in will it move to the next iteration while that 400ms is finishing up, or will the default function wait for everything to finish before it finally finishes itself? Apologies if the question is confusing, not sure of a better way to explain it.

My initial guess is that the execution stalls until the second request finishes anyways?

How can I create a native component of Android in ReactNative using Here Maps SDK

I’m here looking for knowledgment about how to use Here Maps SDK in React Native.
(https://developer.here.com/documentation/android-sdk-explore/4.14.1.0/dev_guide/topics/quick-start.html#say-hello-map)

I know React Native, that part is not a problem. But I can’t say I know how Android works…

My question is about how can I create a full size map in my React Native app, using Fragments.
Following the React Native documentation in order to creat an Android Native UI Component :

I need a custom view:

// replace with your package
package com.mypackage;

import android.content.Context;
import android.graphics.Color;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

public class CustomView extends FrameLayout {
  public CustomView(@NonNull Context context) {
    super(context);
    // set padding and background color
    this.setPadding(16,16,16,16);
    this.setBackgroundColor(Color.parseColor("#5FD3F3"));

    // add default text view
    TextView text = new TextView(context);
    text.setText("Welcome to Android Fragments with React Native.");
    this.addView(text);
  }
}

A Fragment to add views, because I think you can get different fragments with different funcitonalities and views:

// replace with your package
package com.mypackage;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;

// replace with your view's import
import com.mypackage.CustomView;

public class MyFragment extends Fragment {
    CustomView customView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        super.onCreateView(inflater, parent, savedInstanceState);
        customView = new CustomView(this.getContext());
        return customView; // this CustomView could be any view that you want to render
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // do any logic that should happen in an `onCreate` method, e.g:
        // customView.onCreate(savedInstanceState);
    }

    @Override
    public void onPause() {
        super.onPause();
        // do any logic that should happen in an `onPause` method
        // e.g.: customView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
       // do any logic that should happen in an `onResume` method
       // e.g.: customView.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // do any logic that should happen in an `onDestroy` method
        // e.g.: customView.onDestroy();
    }
}

A ViewManager (Honestly I don’t know what the purpose of this is):

// replace with your package
package com.mypackage;

import android.view.Choreographer;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.annotations.ReactPropGroup;
import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.ThemedReactContext;

import java.util.Map;

public class MyViewManager extends ViewGroupManager<FrameLayout> {

  public static final String REACT_CLASS = "MyViewManager";
  public final int COMMAND_CREATE = 1;
  private int propWidth;
  private int propHeight;

  ReactApplicationContext reactContext;

  public MyViewManager(ReactApplicationContext reactContext) {
    this.reactContext = reactContext;
  }

  @Override
  public String getName() {
    return REACT_CLASS;
  }

  /**
   * Return a FrameLayout which will later hold the Fragment
   */
  @Override
  public FrameLayout createViewInstance(ThemedReactContext reactContext) {
    return new FrameLayout(reactContext);
  }

  /**
   * Map the "create" command to an integer
   */
  @Nullable
  @Override
  public Map<String, Integer> getCommandsMap() {
    return MapBuilder.of("create", COMMAND_CREATE);
  }

  /**
   * Handle "create" command (called from JS) and call createFragment method
   */
  @Override
  public void receiveCommand(
    @NonNull FrameLayout root,
    String commandId,
    @Nullable ReadableArray args
  ) {
    super.receiveCommand(root, commandId, args);
    int reactNativeViewId = args.getInt(0);
    int commandIdInt = Integer.parseInt(commandId);

    switch (commandIdInt) {
      case COMMAND_CREATE:
        createFragment(root, reactNativeViewId);
        break;
      default: {}
    }
  }

  @ReactPropGroup(names = {"width", "height"}, customType = "Style")
  public void setStyle(FrameLayout view, int index, Integer value) {
    if (index == 0) {
      propWidth = value;
    }

    if (index == 1) {
      propHeight = value;
    }
  }

  /**
   * Replace your React Native view with a custom fragment
   */
  public void createFragment(FrameLayout root, int reactNativeViewId) {
    ViewGroup parentView = (ViewGroup) root.findViewById(reactNativeViewId);
    setupLayout(parentView);

    final MyFragment myFragment = new MyFragment();
    FragmentActivity activity = (FragmentActivity) reactContext.getCurrentActivity();
    activity.getSupportFragmentManager()
            .beginTransaction()
            .replace(reactNativeViewId, myFragment, String.valueOf(reactNativeViewId))
            .commit();
  }

  public void setupLayout(View view) {
    Choreographer.getInstance().postFrameCallback(new Choreographer.FrameCallback() {
      @Override
      public void doFrame(long frameTimeNanos) {
        manuallyLayoutChildren(view);
        view.getViewTreeObserver().dispatchOnGlobalLayout();
        Choreographer.getInstance().postFrameCallback(this);
      }
    });
  }

  /**
   * Layout all children properly
   */
  public void manuallyLayoutChildren(View view) {
      // propWidth and propHeight coming from react-native props
      int width = propWidth;
      int height = propHeight;

      view.measure(
              View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
              View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));

      view.layout(0, 0, width, height);
  }
}

And next steps are not difficult because they are only steps about how you can connect React Native and Android.

My main problem is Can I use a MapView instance as a View inside of a FrameLayout? And How Can I set a full width/height measure?

Thanks,
Pelayo

How can I add spacing or margin between rows in AG-Grid?

enter image description here

I am trying to create an AG-Grid table with Master/Detail functionality. While working on the styling, I encountered the issue mentioned above. I am also using the autoHeight property set to true.

Below is the code that I am using to style the rows.

getRowStyle: (params: any) => {
    const rowIndex = params.node.rowIndex;

    return {
        backgroundColor: rowIndex % 2 === 0 ? "#c9daf8" : "#6d9eeb",
        marginTop: rowIndex === 0 ? "0" : `${10 * rowIndex}px`,
        borderRadius: "8px",
        border: "none",
    };
},

This is causing some rows to be clipped, as shown in the screenshot. Does anyone know how to solve this problem?

What is the real difference in terms of performance when you extract conditions from an if statement to improve readability? [duplicate]

I’m trying to know how to calculate what is the real impact of changes like the following:

    if ((payload.transactions?.length > 0) &&
        (user.Type === UserType.Premium && user.status === UserStatus.Active)
    ) {
        doSomeStuf();
    }
    const hasTransactions = () => { return payload.transactions?.length > 0; }
    const isActivePremium = () => { 
        return user.Type === UserType.Premium && user.status === UserStatus.Active; 
    }
    
    if (hasTransactions() && isActivePremium()) {
        doSomeStuf()
    }

where conditions are moved from an if statement to a function in order to improve the code readability

How to programatically select an image for (chrome extension manifest v3)

Can a chrome extension (manifest v3) do the following

  • there is a given element
  • I want to automatically have my extension select a JPG for that field so that I can automate some user tasks like uploading images

I’ve seen other chrome extensions do this so that’s why I decided asking, but I also read that this is impossible because of understandable security issues but maybe a specific chrome extension permission could allow this and I’m just not finding it?

Why are React properties not being passed as expected?

Passing props in the app.js is not working while using it in another component (card.js)

Passed props in App.js. But nothing is shown while using it on Card.js

export default function Card(props) {
  
  console.log(props);
  
  return (
    <div className="card">
      <img className="card--image" src={`../images/${props.img}`}></img>
      <div className="card--stats">
        <img style={{ height: 30 }} className="card--star" src={star}></img>
        <span className="bold">{props.rating}</span>
        <span className="gray bold">({props.reviewCount})</span>
        <span className="gray bold">{props.country}</span>
        <p className="bold">{props.title}</p>
        <p>
          <span className="bold">from ${props.price} per person</span>
        </p>
      </div>
    </div>
  );

}

export default function App() {
  return (
    <div>
      <NavBar></NavBar>
      <Hero></Hero>
      <Licence test={"Test123"} />
      <Card>
        img="sports1.webp" rating={"5.0"}
        reviewCount={6}
        country="USA"
        title="Life Lessons with Tiger woods"
        price={120}
      </Card>
    </div>
  );
}

Hide multiple DIV ID elements using Javascript If url has specific text (Already have code that hides one)

I have this script I often use, but I always add it to the code multiple times to hide multiple different things, which bad I believe. How can I add multiple IDs to it so I can hide multiple things

<script type="text/javascript">
  var url = window.location.href;
  var msg = document.getElementById('thisid');
  // Check if URL contains the keyword
  if( url.search( 'thisword' ) > 0 ) {
      msg.style.display = "none";
  }
</script>

For example where it says “thisid”, how do I add another ID within this same code

And also, if possible how can I add another style? I’d like to also have visibility = “hidden”; added as well.

Please, and thank you so much for having read this and helping

How to make random css animation time?

Im now doing project Google Dino, and I want to make a random cactus animation time and delay but I dont know how, here is my code:

`.cactus-anim {
    animation: cactus-move 1.3s 0.5s linear infinite;

}

@keyframes cactus-move {
    0% {
        left: 700px;
    }

    100% {
        left: -40px;
    }
}`

(I want to make instead of 1.3s – random(1-2)s, and instead of 0.5s – random(0-0.7)s , and also Im using Scss and Js, Thnks

http fetch request gets changed to https which leads to an error

I have a problem with the fetch() js method. I have a link which calls a news API and is supposed to return some things (I have tried to retrieve it by running it with node.js which worked) but once I let it be called by my html file in which it should portray the data it doesn’t work anymore.

the fetch code

this is where it says scheme would be https but I want/need http
the error (because I am not allowed to ask https but only http)

I thought it might have been the referrerPolicy but changing that didn’t do much. I also thought if the content-security-policy in the html file has something to do with it but deleting it didn’t change anything either. No idea if I completely missed something I am still new to js and html but my other API requests all worked.

How can I format this array of objects to another object format?

First of all I am sorry If I couldn’t explained my problem because it is really hard for me to explain it but If you need more information I will try answer all. So I am trying to format this array of objects

[
    {
        "time": "18th",
        "open": 100,
        "closed": 60,
        "waiting": 12
    },
    {
        "time": "20th",
        "open": 120,
        "closed": 80,
        "waiting": 75
    },
    {
        "time": "22nd",
        "open": 170,
        "closed": 0,
        "waiting": 34
    },
]

To this in javascript. I don’t know what to do, I am not even sure if I can really format it, I need to create a dynamic chart and I realised that I can’t do it with the first format due to library restrictions.

{
    "time": ["18th", "20th", "22nd"],
    "graphData": [
        {
            "label": "open",
            "data": [100, 120, 170],
        },
        {
            "label": "closed",
            "data": [60, 80, 0],
        },
        {
            "label": "waiting",
            "data": [12, 75, 34],
        }
    ]
}

Should `stripe.confirmCardPayment` emit `incorrect_cvc` error code

Given I have the following stripe client side code inside of a react component:

const stripeResponse = await stripe.createPaymentMethod({
          type: 'card',
          card: elements.getElement('cardNumber'),
          billing_details: {
            address: {
              city: selectedAddress.town,
              country: selectedAddress.country.iso3166Code,
              line1: selectedAddress.line1,
              line2: selectedAddress.line2,
              postal_code: selectedAddress.postalCode,
              state: selectedAddress.region,
            },
            email: "[email protected]",
            name: "form_field_name",
            phone: selectedAddress.phone,
          },
        });

        if (stripeResponse.error) {
          console.log("Should we be able to get Error Codes and Decline Codes?") 
        }



Does stripe.createPaymentMethod allow to see decline and error codes that are mentioned in the documentation? For instance, I am not seeing error code incorrect_cvc for card number 4000000000000127

Reference:
https://stripe.com/docs/testing?testing-method=card-numbers#declined-payments

enter image description here