CSS modification not applying to the project at all?

I created a website to teach blind typing. However, while running it, i noticed that none of my CSS midifications happen… I tried debugging and searching the internet for similar problems but I cannot find the problem myself and so will appreciate a second pair of eyes to look it over and help me resolve this…
Thanks in advance <3

My HTML code:

    <head>

        <title>Blind Typing</title>
        <h2> Learn how to type blindly today! </h2>
        <h4> Follow these simple exercises and become a blind typer! </h4>
        <link rel="stylesheet" href="../blindTyping.css">
        <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
        <script src="../blindTyping.js"></script>

    </head>

    <body>
        
        <div>
        
            <div class="exp">
        
                Copy the following quote, without looking at the keyboard!, to the best of  you ability.
        
            </div>
            
            <div class="menu">
                
                Choose diffeculty level:
                <ul>
                    <li><button class="easy">Beginner</button></li>
                    <li><button class ="mid">Intermediate</button></li>
                    <li><button class="hard">Expert</button></li>
                </ul>
            </div>
        
            <div class="original" id="exc">
        
            </div>
            
            <div id="timer">
            
                <button class="start">start</button>
                <button class="stop">stop</button>
                <p class="timer"></p>
            
            </div>
        
            <div class="copy" id="exc">
        
                <input type="text">
                
                <p id="msg" class="oops" background-color="red"></p>
                <p  id="msg" class="success" background-color="green">Congratulation! You made it! Now go and try the next one! </p>
            
                <button class="under" id="next">Next Exercise</button>
                <button class="under" id="return">Return to Menu</button>
                
            </div>
        </div>

    </body>

</html>

My javascript code:

/*global $, document*/

var easy = ["This is a test", "This is another test"];
var med = ["This is a medium quote"];
var hard = ["This is a hard quote"];

var cntq, currIndex = 0, mistakes = 0;

$(document).ready(function () {
    "use strict";
   
    $("#exc").hide();
    $(".oops").hide();
    $(".success").hide();
    $(".stop").hide();
    
        
$(".easy").on("click", function () {
    cntq = easy;
    $("#exc").show();
    $(".menu").hide();
    $(".original").html("<p>"+easy[currIndex]+"</p>");
});
    
$(".mid").on("click", function () {
    cntq = med;
    $("#exc").show();
    $(".menu").hide();
    $(".original").html("<p>"+med[currIndex]+"</p>");
});
    
$(".hard").on("click", function () {
    cntq = hard;
    $("#exc").show();
    $(".menu").hide();
    $(".original").html("<p>"+hard[currIndex]+"</p>");
});
    
$("#next").on("click", function () {
    currIndex++;
    mistakes = 0;
});
    
$("#return").on("click", function () {
    $("#exc").hide();
    currIndex = 0;
});
    
$("input").on("input propertychange", function () {
    $(".oops").hide();
    $(".success").hide();
    var chk = $("input").val();
    var org = cntq[currIndex];
    var errorFound = false;
    var newHTML = "";
        
    // Check letter by letter if the input matches the original sentence
    for(var i=0; i<chk.length&&!errorFound;i++){
        if(chk[i]===org[i]){
            // Add mark tag to the current letter in the original text to show user progress
            newHTML = newHTML +"<mark>"+org[i]+"</mark>";            }
        else{
            // If there's a mistake, alert user and delete the input so user can try again
            newHTML = cntq[currIndex];
            mistakes++;
            errorFound = true;
        }
    }
        
    // Check if there was a mistake
    if(errorFound){
        $(".oops").text("Oops! You made " + mistakes+ " mistakes.");
    }
        
    // complete the original sentence if the input is still unfinished with the rest of the org sentence
    if(i != org.length){
        for(;i<org.length;i++){
            newHTML+=org[i];
        }
    }// Check whether the sentence matches the original completely
    else if (newHTML === org){
        $(".success").show();
    }
        
    $(".orginal").html(newHTML);
    $("mark").attr("background-color='yellow'");
});
   
function getdate(){
    var today = new Date();
    //var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    if(s<10){
        s = "0"+s;
    }
    if (m < 10) {
        m = "0" + m;
    }
    $(".timer").text(m+" : "+s);
    $(".start").hide();
    $(".stop").show();
    setTimeout(function(){getdate()}, 500);
}

$(".start").on("click", getdate);

$(".stop").on("click", function() {
    $(".start").show();
});
    
}); // End ready function

My CSS code:

title h2 h4 {
    left: 50%;
    transform: translate(-50%,0);
    text-align: center;
    position: absolute;
    border-radius: 5px;
    box-shadow: 0px 8px 16px 0px;
}

body {
    left: 50%;
    transform: translate(-50%,0);
    text-align: center;
    position: absolute;
    border-radius: 5px;
}

ul .menu {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

li button {
    display: block;
    width: 60px;
}

mark {
  background-color: yellow;
  color: black;
}

input 
{
    display: block;
    width: 500px;
    height: 200px;
}

.under {
    display:inline-block;
}

#next {
    float: right;
    position: absolute;
}

#return {
    float: left;
    position: absolute;
}

p #msg {
    border-radius: 10px;
    padding: 20px;
    width: 500px;
    height: 50px;
}

.oops {
    border: 2px red
}

.success {
    border: 2px green;
}

#timer {
    right: 5%;
    text-align: center;
    position: absolute;
    border-radius: 5px;
    box-shadow: 0px 8px 16px 0px;
}

Reactjs/Redux – Objects are not valid as a React child

I am making a shopping cart – onClick I have redux adding items to cartItems array.

In the code below (increment reducer its the last one after add/remove) I am trying to get rid of duplicate values from the cartItems array, and display a total number of unique items in the cart with cartIcon: {value: 0} – which is by default 0 (before adding any items).


const initialState = {
    cartItems: [],
    cartQuantity: 0,
    cartIcon: {value: 0},
}


export const addToCartSlice = createSlice({
    name: 'cart',
    initialState,
    reducers: {
        
        add(state, action ) {

            const itemIndex = state.cartItems.findIndex(
                (props) => props.id === action.payload.id
                );
                if(itemIndex >= 0){
                    state.cartItems[itemIndex].cartQuantity += 1;
                } else {
                    const tempProduct = {...action.payload, cartQuantity: 1}
                    state.cartItems.push(tempProduct);

                }

            
        },
        remove(state, action) {
            const removeItem = state.cartItems.filter(
                (cartItem) => cartItem.id !== action.payload.id 
            
            );
            state.cartItems = removeItem;
        },


        increment: (state) => {
            const Items = state.cartItems.filter(
                (element, index) => state.cartItems.indexOf(element) === index);
                state.value = Items.length;
        }      // if i just do state.value += 1
               // then the value goes up by 1
               // but I want to display the amount of unique entries

    },

});

Here onClick I am pulling data from the item that was “added” to the cart and additionally trying to increment the cartIcon number by 1 (if the item hasn’t been yet added to the array cartItems). The problem could be here? Because the error mentions all the props and data I’m pulling to be rendered into the cart.

const dispatch = useDispatch()
const handleAddToCart = (props) => {
  dispatch(add(props));
};

  return (<>
                <div id={props.id} className='shopitem'>
                    <img src={props.url} />
                    <h2>{props.title}</h2>
                    <p className='boldprice'>${props.price}</p>
                    <button onClick={() => {
                    handleAddToCart(props);
                    dispatch(increment())
                  }}> ADD TO CART </button>
                </div>
        </>
  )
}

And here I am trying to display the amount of unique items to the shopping cart icon.

const count = useSelector((state) => state.cart.cartIcon.value)
{count}

For some reason I am getting this error. If I just do state.value += 1 it will add +1 to the shopping cart icon, however I only want to display +1 for each unique item.

“Uncaught Error: Objects are not valid as a React child (found: object with keys {id, title, price, url, cartQuantity}). If you meant to render a collection of children, use an array instead.”

Please help – I am relatively new to Javascript and programming overall.. I may be making a stupid mistake, so if something is clearly wrong.. then please let me know 🙂

Angular hot observables with RxJS: Changes on array are not emitted to subscribers

I have a small task board like trello with tasks to be done, doing and done. All the tasks are stored on 3 separate arrays in one service called TaskService. To show the task and change task state I have implemented angular’s cdk drag n drop.

My goal now is to subscribe to the the task arrays so when the array changes send the changes to an api. For now I’m just trying to console.log the events but I’m not understanding what’s happening it seemly to work but I can’t get the arrays updates.

This is my component controller:

doing: any[];

  constructor(private taskService: TaskService) {}

  ngOnInit(): void {
    this.getTodoTasks();
    // this.getDoingTasks();
    this.getDoneTasks();

    const obs$ = this.taskService.getDoing();

    obs$.subscribe({
      next: (data: any[]) => {
        this.doing = data;
        console.log(data);
      },
    });
  }

  todo: any[];
  // doing: Subscriber<any[]>;
  done: any[];
  newTaskText: string = '';

  isModalShown: boolean = false;

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer == event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }

  newTask() {
    console.log(`Click Modal!`);
    this.isModalShown
      ? (this.isModalShown = false)
      : (this.isModalShown = true);
  }

  getTodoTasks() {
    this.taskService.getTodos().subscribe((data) => {
      this.todo = data;
      console.log(`Se ha añadido Tak a : Todo`);
    });
  }

This is my view:

<app-modal *ngIf="isModalShown" (close)="newTask()">
  <div class="modalContent">
    <textarea
      name=""
      id=""
      cols="30"
      rows="10"
      class="newTask"
      [(ngModel)]="newTaskText"
    ></textarea>
    <div class="modalButtons">
      <input
        type="button"
        value="Cancel"
        class="btn btn-secondary"
        (click)="cancelTask()"
      />
      <input type="button" value="Save" class="btn btn-primary" (click)="saveTask()" />
    </div>
  </div>
</app-modal>

<div class="container">
  <div class="list">
    <h2>TO DO</h2>
    <input type="button" value="Modal" (click)="newTask()" />
    <div
      class="tasks"
      cdkDropList
      #todoList="cdkDropList"
      [cdkDropListData]="todo"
      [cdkDropListConnectedTo]="[doingList, doneList]"
      (cdkDropListDropped)="drop($event)"
    >
      <div class="task" *ngFor="let item of todo" cdkDrag>{{ item }}</div>
    </div>
  </div>
  <div
    class="list"
    cdkDropList
    #doingList="cdkDropList"
    [cdkDropListData]="doing"
    [cdkDropListConnectedTo]="[doneList, todoList]"
    (cdkDropListDropped)="drop($event)"
  >
    <h2>DOING</h2>
    <div class="tasks">
      <div class="task" *ngFor="let item of doing" cdkDrag>{{ item }}</div>
    </div>
  </div>
  <div
    class="list"
    cdkDropList
    #doneList="cdkDropList"
    [cdkDropListData]="done"
    [cdkDropListConnectedTo]="[doingList, todoList]"
    (cdkDropListDropped)="drop($event)"
  >
    <h2>DONE</h2>
    <div class="tasks">
      <div class="task" *ngFor="let item of done" cdkDrag>{{ item }}</div>
    </div>
  </div>
</div>

And my service:

constructor() {}

  todo = ['task 1', 'task 2', 'task 3'];
  doing = [];
  done = [];

  getTodos(): Observable<any[]> {
    return of(this.todo);
  }

  getDoing(): Observable<any[]> {
    return new Observable((subscriber) => {
      subscriber.next();
    })
  }

  getDone(): Observable<any[]> {
    return of(this.done);
  }

How to create a element and then make that element draggable across the page?

I need to create a element with documet.createelement and make it draggable. Here is the code

    var files= document.getElementById('texttouse').value;
    let textadder=document.createElement("p");
 let t= document.createTextNode(files);
 textadder.appendChild(t);
   document.getElementById('gallery').appendChild(textadder);
     for (i = 0 ; i < textadder.length; i++) {
    textaddder[i].onclick = function() {
      var div = this.parentElement;
     
    }
  }             
  
}

But I can’t figure out how to make it draggable.Please help me.

How to pass javaScript value in view page to Controller Action parameter, when change drop down list

I want to pass student Id in my controller action, I used JsonResult action, I catch student id but can’t pass in action,

this is my JavaScript code ,

<script type="text/javascript">
    $(document).ready(function () {
        $("#sId").change(function(){
            var studentId = $(this).val();
            debugger
            $.ajax({
            type:"post", 
            url:"/Department/GetDeptName/" + studentId,
            contentType:"html",
            success:function(response){
            debugger
            $("#dId").empty();
            $("#did").append(response);
            }
            })
        })
    });
</script>

And I have a Dropdown list, I pass my list fron database using ViewBag. When I select a student name then need to pass his/her department name. This is the view code

<div class="row">
            <div class="col-md-6 mb-4">
                <label asp-for="Name" class="control-label">Student Name</label>
                <select asp-for="Id" class="form-control" id="sId"
                        asp-items="@(new SelectList(@ViewBag.messageStudent,"Id", "Name"))">
                </select>
            </div>
            <div class="col-md-6 mb-4">
                <label asp-for="DeptName" class="control-label">Department Name</label>
                <input asp-for="DeptName" id="dId" class="form-control mb-3"  type="text" placeholder="Dept Name" disabled>
            </div>

            <input type="hidden" asp-for="Id" name="Id" id="DeptName" />

        </div>

This is my controller code that is passed a list from database to View

    public async Task<IActionResult> DropDown()
    {
        var model = _scope.Resolve<FormModel>();

        await model.LoadStudenDataAsync();
        var studentList = model.StudentList.ToList();

        studentList.Insert(0, new Student { Id = 0, Name = "Select Group" });

        ViewBag.messageStudent = studentList;
        return View(model);
    }

Now I need to pass student id from view page, if i pass student id then I solve my problem,
This is my JsonResult Action

    public async Task<JsonResult> GetDeptName(int studentId)
    {
        var model = _scope.Resolve<FormModel>();

        if (ModelState.IsValid)
        {
            await model.DeptList(studentId);
        }

        return Json(model);
    }

Please help me anyone how to pass student id,Thanks in Advance

Best way to filter an array of objects by Index in JavaScript

I have an array of objects like this

export const productArray = [

  { 
    imgUrl: images.beautifulinwhite,
    productName: "White Flowers",
    oldPrice: "$45.99",
    newPrice: "$35.99",
  },
  {
    imgUrl: images.blueandpinkjeans,
    productName: "Blue and Pink Jeans",
    oldPrice: "$57.99",
    newPrice: "$40.99",
  },
  {
    imgUrl: images.girlinyellow,
    productName: "Yellow Tshirt",
    oldPrice: "$53.99",
    newPrice: "$37.99",
  },
  {
    imgUrl: images.ladyinblack,
    productName: "Black Hoodie",
    oldPrice: "$40.99",
    newPrice: "$33.99",
  },
]

How do I filter this array to only get the first two objects? I don’t want to filter them by their attributes. I want to filter using their indexes .

React Native Button taking CSS of Previous Button

I am setting Buttons stack on the basis of a variable whether channel is joined or not.
One button is “Join Channel” which a plain text button
Second button is “End Call” button which is a Circular button with an icon.
Both have different CSS.
When I click on “Join Channel”, channel is joined and my stack is changed.
Then I click on “End call” button, but CSS of this button does not remove and applied to “Join Channel” Button. Background color is not removed.

Rendering Code:

{this.state.isJoined ? this._callButtonsView() : this._joinButtonView()}
_joinButtonView = () => {
    return (
      <View style={styles.buttonsContainer}>
        <Button
          title="Join Channel"
          buttonStyle={styles.joinButton}
          titleStyle={{color: 'green', fontSize: 20}}
          onPress={() => this._joinChannel()}
        />
      </View>
    );
  };

  _callButtonsView = () => {
    return (
      <View style={styles.buttonsContainer}>
        <Button
          icon={{
            name: 'call-end',
            color: '#ff0000',
            size: 25,
          }}
          buttonStyle={styles.actionButton}
          onPress={() => this._leaveChannel()}
        />
      </View>
    );
  };

CSS:

actionButton: {
    backgroundColor: 'blue',
    padding: 0,
    height: 50,
    width: 50,
    marginRight: 25,
    marginTop: 5,
    marginBottom: 5,
    borderRadius: 25,
  },
  joinButton: {
    backgroundColor: 'clear',
  },

Video:

enter image description here

image is coming over input element in react js

when I launch the page, the browser extension icon(marked in red) is static and it is at the beginning.

enter image description here

when I type it keeps moving and covers the last typed text.

enter image description here

is there any css property through which I can prevent it coming on my component. I alredy tried

  input{
     background:none !important
     background-image:none !important
  }

but its not working.

I am using react and .scss file for css. this issue is not in other elements or components.

Can’t find the way to calculate and output it

I’m trying to get the percentage from the “timeSpend” and “breakTime” and store in fSubject,sSubject, tSubject and store it in dataset: date[],
so that it can output it but it just gives the value of “timeSpend” and “breakTime” not fSubject,sSubject, tSubject enter image description here

 let timeSpend = document.querySelector("#time_spend").value;
let breakTime = document.querySelector("#break_time").value;
let fSubject = document.querySelector("#first_subjects").value;
let sSubject = document.querySelector("#second_subjects").value;
let tSubject = document.querySelector("#third_subjects").value;

let fSubjectV = (50/100) * (timeSpend + breakTime); 
let sSubjectV = (25/100)* (timeSpend + breakTime);
let tSubjectV = (25/100)* (timeSpend + breakTime);

let myChart = document.getElementById("myChart").getContext("2d");

document.querySelector("button").addEventListener("click", () => {
    let pieChart = new Chart(myChart, {
        type: "pie",
        data: {
            labels: [
                "Time spend",
                "Break Time",
                "First Subject",
                "Second Subject",
                "Third Subject",
            ],
            datasets: [
                {
                    label: "Plan",
                    data: [
                        timeSpend.value,
                        breakTime.value,
                        fSubjectV.value,
                        sSubjectV.value,
                        tSubjectV.value,
                    ],
                },
            ],
        },
        options: {},
    });
});

PHP nl2br for text content but make it exclude on javascript content

I need to use nl2br function on page content coming from DB. But <br /> tag added to into javascript content too.

<script type="text/javascript"><br />
let test = "test";<br />
let menu = "menu";<br />
</script>

Firstly for make add br to all content and than remove br from javascript content, I did try this:

<?php
//content coming from db
$content = nl2br($content);
$content = preg_replace("/<scriptb[^>]*>([sS]*?)</scriptb[^>]*>/m", str_replace("<br />", "", nl2br($content)), $content);
echo $content;
?>

Result: br not added into javascript but javascript and text content did come twice (br didn’t worked on first text content but worked on second text content)

How can I exclude br in javascript code?

Cannot show image by img.src

I have no idea why setting img.src with import is fine but when I pass the path to it doesn’t work.

import mahjong_tiles from '../assets/mahjong_tiles/1man.png'

const displayTileArr = () => {
    var img = document.createElement('img');
    img.src = mahjong_tiles ; //OK
    img.src = '../assets/mahjong_tiles/1man.png';  //NOT OK
    document.getElementById('display-hand').appendChild(img);   
}

How do I hide all objects in a “source” (geoJson) in MapBox GL JS based on whether their description matches my string?

I’ve long tried to implement this feature for my map system, because I have lots of markers loaded in and it’s very useful to be able to enter a string such as “abc” into an input field to “filter out” (visually hide) all the ones that don’t contain that string inside of their description/title.

A few weeks ago, I found this example: https://docs.mapbox.com/mapbox-gl-js/example/filter-markers/

Unfortunately, they do it in a completely silly manner which doesn’t apply to my situation, so I was only able to grab the basic input part from their example. Then I got stuck. I tried countless things and after many hours of work, I at least have finally managed to be able to loop through my loaded-in geoJson “sources” (containing all the markers). So, I have this:

filterInput.addEventListener('keyup', (e) =>
{
    const value = e.target.value.trim().toLowerCase();

    let sources = Object.entries(map.getStyle().sources);

    for (const source of sources)
    {
        if (source[1].type == 'geojson')
        {
            console.log(source[0]); // The name of the source, for example "my nostalgic visited places".
            
            // Here, I'm trying to loop through all the inidividual markers of this geoJson "source" and, based on "value" and its title/description, either visually hide or display it. This is the part I just cannot figure out.
        }
    }
});

I obviously need to loop through the markers inside each geoJson inside my sources for loop, but how? I don’t know:

  1. How to actually loop through those in the first place. I can’t find any in the source object.
  2. How to tell MapBox GL JS to hide/show them individually. The example that they have just bulk hide/show entire layers/sources, which is irrelevant.

If it helps, console.log(source[1]); causes this kind of output:

{type: 'geojson', data: 'http://127.0.0.1/mymap/geoJSON/my nostalgic visited places.geojson'}
data: "http://127.0.0.1/mymap/geoJSON/my nostalgic visited places.geojson"
type: "geojson"
[[Prototype]]: Object

Disappointingly, the [[Prototype]]: Object does not seem to contain any neat array of markers, as I first assumed would be the case. I don’t know what to make of it.

JS button must be clicked twice on first use – why?

I have two buttons on a web page (Previous and Next) and both have a function associated with their click event:

//Add click events for the next and previous buttons
document.getElementById("previous").addEventListener("click", selectSection);
document.getElementById("next").addEventListener("click", selectSection);

The code for selectSection is:

Blocking and non blocking code in parallel

I need to be able to run some code that is going to be blocking and some other code that will then, when blocked, start some other actions.

The usecase is the follows:

I have a file called index.ts running an express and socket server

I have a testfile called test.spec.ts that needs to be able to start the express server and then initiate some commands for running tests either via HTTP request or socket message(I would prefer HTTP)

The only way I found to keep the webserver alive is instanciating it with

import { spawnSync } from 'child_process';

spawnSync('ts-node', ['path/to/index.ts"], { cwd: "path/to/workdir"});

which will block until the child process is killed( could be up to 30min later).

Is there a way to split into two processes, one that gets blocked when starting it and one continuing to work that exposes some functions for interactions with the test file?

My target would look like this:

// index.ts

import * as express from "express";
const app = express();

const port = 3000;

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});
// test.spec.ts

import { spawnSync } from 'child_process';

describe("Test",()=>{

  it("Test", async ()=>{

    // create somehow a child process that should block
    const childProcess = ...
    childProcess.do(spawnSync('ts-node', ['path/to/index.ts'], {cwd: 'path/to/workdir'}) //should block now

    // the following code should run in parallel
    await new Promise(r => setTimeout(r, 5000)); //wait some time until the webserver is ready

    fetch('http://localhost:3000').then((ret)=>{
      expect(ret,'to be Hello World').to.contain('Hello World!");
    })
    ... // more tests
  });
});

How to replace a substring between two indexes ignoring HTML tag in JavaScript

I want to replace a substring in a text between two indexes. But I want to ignore any HTML tag when counting the index.

For example

If the text is the best kitchen knife I want to replace the substring from index 4 to 8 with ‘nice’ so the output should be the nice kitchen knife

But if the text is in HTML tag like
<li>the best kitchen knife</li>
or
<li>the <span>best</span> kitchen knife</li> and given indexes are 4 and 8, it should count from ‘the’ not from <li>. So the expected output should be <li>the <span>nice</span> kitchen knife</li>

I used the following code but it doesn’t work as I’m expecting.

function replaceBetween(origin, startIndex, endIndex, insertion) {
    return (
        origin.substring(0, startIndex) + insertion + origin.substring(endIndex)
    );
}

Usage:

replaceBetween("<li>the <span>best</span> kitchen knife</li>", 4, 8, "nice");

Output:

<li>nice<span>best</span> kitchen knife</li>

Expected Output:

<li>The <span>nice</span> kitchen knife</li>