Catch block not executed when error is thrown from Try block within setTimeOut In Javascript

[![enter image description here][1]][1]I am trying to throw an exception from setTimeout within the try block.
See Below Code

    let a = 2 + 2;
    if (a == 4) {
        setTimeout(() => {
            console.log('Set time out')
            throw new Error()
        }, 3000)
    }
    else {
        console.log('Not 4')
    }

} catch (error) {
    console.log('catch block')
    console.log(error)
}```

But the control cannot come to the catch block and I am unable to see the result from console.log('catch block').


  [1]: https://i.stack.imgur.com/3DdhB.png

Cannot find name ‘BarcodeDetector’

I’m trying to create a new BarcodeDetector class as the example shows on MDN but I’m getting the above error.

let barcodeDetector = new BarcodeDetector({ formats: ['qr_code'] });

here is a link to a Stackblitz showing the error using angular 12.

any idea why?

How to arrage the data as rows and columns?

I have used my map function to iterative over the data and print it out. But I was unable to separate it as rows and columns.
There should be 5 columns that are fixed and the rows change dynamically, that is the reason I cannot use array indexing.

I am attaching reproducable code – Link

let array = [
    [
        72.3474349975586,
        83.77342224121094,
        83.77342224121094,
        72.3474349975586,
        97.0778579711914
    ],
    [
        80.1422348022461,
        93.16133117675781,
        93.16133117675781,
        80.1422348022461,
        108.54068756103516
    ],
    [
        108.37809753417969,
        125.22685241699219,
        125.22685241699219,
        108.37809753417969,
        147.92010498046875
    ],
    [
        163.5850372314453,
        197.7432098388672,
        197.7432098388672,
        163.5850372314453,
        228.80577087402344
    ],
    [
        198.08128356933594,
        236.1764678955078,
        236.1764678955078,
        198.08128356933594,
        276.9237060546875
    ],
    [
        126.81776428222656,
        147.2906951904297,
        147.2906951904297,
        126.81776428222656,
        174.1883544921875
    ],
    [
        95.24028778076172,
        110.93660736083984,
        110.93660736083984,
        95.24028778076172,
        129.43946838378906
    ],
    [
        95.24028015136719,
        110.93661499023438,
        110.93661499023438,
        95.24028015136719,
        129.43946838378906
    ],
    [
        126.8177719116211,
        147.2906951904297,
        147.2906951904297,
        126.8177719116211,
        174.1883544921875
    ],
    [
        198.081298828125,
        236.176513671875,
        236.176513671875,
        198.081298828125,
        276.9237060546875
    ],
    [
        163.5850372314453,
        197.74327087402344,
        197.74327087402344,
        163.5850372314453,
        228.80577087402344
    ],
    [
        108.37812042236328,
        125.22686767578125,
        125.22686767578125,
        108.37812042236328,
        147.92013549804688
    ],
    [
        80.1422348022461,
        93.16131591796875,
        93.16131591796875,
        80.1422348022461,
        108.54067993164062
    ],
    [
        72.347412109375,
        83.77342987060547,
        83.77342987060547,
        72.347412109375,
        97.07785034179688
    ],
    [
        80.1422348022461,
        93.16131591796875,
        93.16131591796875,
        80.1422348022461,
        108.54067993164062
    ],
    [
        108.37812042236328,
        125.22686767578125,
        125.22686767578125,
        108.37812042236328,
        147.92013549804688
    ],
    [
        108.37809753417969,
        125.22685241699219,
        125.22685241699219,
        108.37809753417969,
        147.92010498046875
    ],
    [
        80.1422348022461,
        93.16133117675781,
        93.16133117675781,
        80.1422348022461,
        108.54068756103516
    ]
]

var num = array.map(function(subarray){
  return subarray
  })


for(i=0;i<num.length;i++){
  for(j=0;j<5;j++){
    console.log(num[i][j])
  }
}

The output I am getting is shown in the figure

enter image description here

But I need something like this, but with 5 columns and rows changing dynamically based on the RestApi.

enter image description here

[Note: the values in the image and code may change as they are kept for reference. I am getting values from RestApi so they keep on changing.

How do I change the location of the pushed array items by clicking on a day item with Vue3?

Here’s my calendar row with day items in it:

enter image description here

The problem is…

…when I select another day, let’s say 13th of Monday, and after that try to add new tasks they still push to the task array of the first day.

Let me just show you:

enter image description here
On the Image above I switch to Monday, and the task list is empty as it should be by default, looks pretty good to me….but…

enter image description here

After I try to add new tasks, it didn’t add any to the selected day, but just pushed them into the first one (I added two more, there were 3 on the first screen)

Let me show you the code:

This is my main component in which all other’s are used in:
Main.vue

setup() {
    // Create days:
    const currDay = ref({});
    const dayArr = ref([]);

    // Just a library for working with dates:
    const moment = require("moment");
    const daysRemainingThisMonth = moment()
      .endOf("month")
      .diff(moment(), "days");
    /*=============================================
        =            Firebase            =
    =============================================*/
    const { user } = useAuthState();
    const auth = getAuth();

    const router = useRouter();
    const signOutUser = async () => {
      try {
        await signOut(auth);
        router.push("/auth");
      } catch (e) {
        alert(e.message);
      }
    };
    /*=====  End of Firebase  ======*/
    const store = useStore();

// Generate the day data:
    const fillDayArray = () => {
      dayArr.value = Array(daysRemainingThisMonth)
        .fill("")
        .map((item, index) => {
          return {
            currDay: moment().add(index, "day").format("D"),
            dayOfWeek: moment().add(index, "day").format("dddd"),
            tasks: [ ],
            id: Math.floor(Math.random() * new Date()),
          };
        });
      currDay.value = dayArr.value[0];
    };

    const updateCurrDay = (value) => {
      currDay.value = value;
    };

    onMounted(() => {
      fillDayArray();
    });

Template of Main.vue:

<template>
  <div id="main">
    <!-- ! Top Level: -->
    <div class="auth"></div>

    <div class="greeting-block">
      <button @click="signOutUser">Sign Out</button>
      <h1 id="greet-user">{{ user?.email }}</h1>
    </div>

    <div class="header-container">
      <Header />
      <Menu />
    </div>

    <div class="calendar-display">
      <Calendar 
          :dayArr="dayArr"
          @updateCurrDay="updateCurrDay"
      /> 
    </div>

    <div class="task-list">
      <TaskView 
          v-if="dayArr.length"
          :dayArr="dayArr"
          :currDay="currDay" 
      />
    </div>
  </div>
</template>

Component where the tasks are rendered: TaskView.vue

 props: {
    dayArr: {
      type: Array,
      default: () => [],
    },
    currDay: {
      type: Object,
      default: () => ({}),
    },
  },
  setup(props) {
    const store = useStore();

    const dayArrData = ref(props.dayArr);
    const currDay = ref(props.currDay);

    const getClickedTask = (item) => {
      store.state.clickedTask = item;

      store.state.cardStatus
        ? (store.state.cardStatus = false)
        : (store.state.cardStatus = true);
    };
    // ! Delete Item:
    const deleteItem = (idx) => {
      currDay.value.tasks.splice(idx, 1);
    };

   // ====== How do I tell it to push items to the currDay? ======
    const addItem = () => {
      currDay.value.tasks.push({
        name: "Empty Task" + Math.random().toString().substring(0, 4),
        description: "No description...",
      });
 
    };


    console.log(currDay.value);
    onMounted(() => {});
    

    return {
      getClickedTask,
      deleteItem,
      addItem,
      dayArrData,
    };
  },

Template of TaskView.vue:

<template>
  <div>Active card: {{ currDay }}</div>
  <hr />
  <div>Current Task is: {{ currDay.dayOfWeek }}</div>
  <div class="task-wrapper">
    <p id="task-counter">Tasks Today: {{ currDay.tasks.length }}</p>
    <div class="task-counter-wrapper">
      <!-- ? Render if there are no tasks available: -->
      <div class="empty-msg" v-if="currDay.tasks.length == 0">
        <p>Start by adding a New Task!</p>
      </div>

      <div class="task-list" v-for="(task, idx) in currDay.tasks" :key="idx">
        <div class="list-item">
          <div class="container">
            <input class="list-checkbox" type="checkbox" />
              {{ task.name }}
          </div>

          <div class="item-actions">
            <button class="edit-item btn" @click="getClickedTask(task)">
              <img class="icon" src="./Images/editing.png" />
            </button>

            <button class="delete-item btn" @click="deleteItem(idx)">
              <img class="icon" src="./Images/delete.png" />
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="item-card">
      <ItemCard />
    </div>

    <div class="add-task-wrapper">
      <button id="add-task-btn" @click="addItem()">+ Add a new task</button>
    </div>
  </div>
</template>

Call object function in RequireJS

I use RequireJS to load some scripts.

Now I would like to create some own methods which also needs the loaded script. I’ve tried a lot but I always get Uncaught (in promise) ReferenceError: hd is not defined

Calling the method ‘connect’:

hd.connect.call(token);

JS

...
require.config({

shim: {
    'socket.io': {
      exports: 'io'
    },
    'socket.io-stream': {
      exports: 'ss'
    }
  },
  paths: {
    'socket.io': WEBSOCKET_PROXY_HOST + '/socket.io/socket.io',
    'socket.io-stream': WEBSOCKET_PROXY_HOST + '/socket.io-stream/socket.io-stream'
  },
  waitSeconds: 1

});

requirejs([
  'socket.io', 'socket.io-stream'
], function(io, ss) {

  // Setup Methods & Events

  const hd = {

    connect : function(token) {
      // Connect to Socket, Proxy Server & authenticate
      socket = io(WEBSOCKET_PROXY_HOST, {
        auth: {
          token: token
        }
      }).on('connect', function(data) {
        socketConnected = true;
        isStreaming = false;
        console.log('connected to socket');
        if (activeRecording) {
          //#startRecording();
        }
      });
...

accessing passed data on front end

I have this on the node.js backend:

var getschedule = "select * from SCHEDULE"
console.log(getschedule);
ibmdb.open(ibmdbconn, function(err, conn) {
    if (err) return console.log(err);
    conn.query(getschedule, function(err, rows) {
        if (err) {
            console.log(err);
        }

        console.log(rows)
        
        res.render("calendar.ejs", {data: rows, trainerFirstName: req.session.firstname, trainerLastName: req.session.lastname});

        conn.close(function() {
        });
    });
});

and as you can see I am passing data: rows. Now in my <script> on the front end, i want to access all the data inside data, which i am passing. how can i do this?

delete an object in an array based on index at level 1 and level 2

I have a array of object which has sub arrays, I want to delete the subarray object based on the index from both the levels.

For example if want to delete object with id:12 I should pass firstIndex = 0 and secondIndex = 1;
Pls note above mentioned eg: is for better understanding of question and not to delete element by id should be deleted based on index only(use case is different and index are received from different source).

const array = [
    {
        id: 1,
        row: [
            {id: 11, value: x},
            {id: 12, value: y},
            {id: 13, value: z},
        ],
    },
    {
        id: 2,
        row: [
            {id: 21, value: a},
            {id: 22, value: b},
            {id: 23, value: c},
        ],
    }
]

firstIndex = 1, secondIndex = 2

const result = [
    {
        id: 1,
        row: [
            {id: 11, value: x},
            {id: 12, value: y},
            {id: 13, value: z},
        ],
    },
    {
        id: 2,
        row: [
            {id: 21, value: a},
            {id: 22, value: b},
        ],
    }
]

firstIndex = 0, secondIndex = 1

const result = [
    {
        id: 1,
        row: [
            {id: 11, value: x},
            {id: 13, value: z},
        ],
    },
    {
        id: 2,
        row: [
            {id: 21, value: a},
            {id: 22, value: b},
            {id: 23, value: c},
        ],
    }
]

const result = array.map((el, i) => (i === firstIndex) && el.rows.map(elm, (elm, index) => (index === secondIndex ) && elm.splice(index, 1)))

Active menu item NOT based on URL but based on a variable

I want to have a Menu with active items on my website. It should be added a class to activate the item. Since the project has cryptic URLs, URL-based solutions are not possible. The text of the respective menu item is shown in the respective page title.

My idea was to compare the pagetitle id="navtopheader" with the text in the menu item. If it is equal, add the menuactive class to the respective menu item.

My HTML looks basically like this:

<div id="navtopheader" class="navtopheader">menu item 1</div>
...
<div class="nav_ebene_2">
   <p>menu item 1</p>
</div>
<div class="nav_ebene_2">
   <p>menu item 2</p>
</div>
...

I can do it actually in an inefficient way:

var headertext = document.getElementById("navtopheader").innerText

var menutext0 = document.getElementsByClassName("nav_ebene_2")[0].innerText
var navlist = document.getElementsByClassName("nav_ebene_2");
if (headertext == menutext0) {
    navlist[0].classList.add("activemenu");
}

var menuitem1 = document.getElementsByClassName("nav_ebene_2")[1].innerText
if (headertext == menuitem1) {
    navlist[1].classList.add("activemenu");
}
...

But since the number of menu items varies across the website, i would get an error message if i include too much/too few menu items.

Is there an appropriate solution? I tried the whole day but didn’t solve the problem. Thank you!

Mocking Controller dependency in Nestjs

I am trying to mock my controller using nestjs createTestingModule and I have added overrider provider to mock the service but it still giving me this error(Screenshot attached screenshot). Kindly help.

I also tried added the other dependencies too but the error is same

Here is my controller.ts file

import {Body, NotFoundException, OnModuleInit, Param, Patch} from "@nestjs/common";
import {BitvavoService} from "./bitvavo.service";
import {DeleteMethod, GetMethod, PostMethod, PatchMethod} from "../../../../global/operations";
import {ApiController} from "../../../../utils/endpoints/api-controller.decorator";
import bitvavo, {BitvavoOrderResponse} from "bitvavo";
import {Repository} from "../../../repository/repository";
import {BitvavoTarget} from "./bitvavo-target";
import {RepositoryFactory} from "../../../repository/repository-factory.service";
import {CollectionNames} from "../../../repository/collection-names";
import {ProducerTargetBindingService} from "../../producer-target-binding/producer-target-binding.service";
import {User, UserClass} from "../../../../utils/endpoints/user.decorator";
import {Permissions} from "../../../../utils/endpoints/permissions.decorator";
import {Permission} from "../../../../utils/permission.enum";
import {EncryptionService} from "../../../encrypt/encrypt.service";
import {
  BitvavoBalanceDto,
  BitvavoPlaceOrderDto,
  BitvavoSingleTargetResponse,
  CreateBitvavoTargetDto,
  UpdateBitvavoTargetDto,
  ChangeBitvavoTargetMode,
  SellSingleBot
} from "./bitvavo-dtos";
import {toTargetDto} from "../target-dto";
import {ApiBotService} from "../../signal-producers/implementers/api-bot/api-bot.service";

const getBalances = async function (target: BitvavoTarget, decryptedKey: string, decryptedSecret: string) {
  try {
    const client = createBitvavoClient(decryptedKey, decryptedSecret);
    return (await client.balance({})).map(balanceToDto);
  } catch (e) {
    return null;
  }
};

@ApiController("signal-targets/bitvavo")
export class BitvavoController implements OnModuleInit {
  private repository: Repository<BitvavoTarget>;

  async onModuleInit() {
    this.repository = await this.repositoryFactory.create(BitvavoTarget);
  }

  constructor(
    private bitvavoService: BitvavoService,
    private repositoryFactory: RepositoryFactory,
    private producerTargetBindingService: ProducerTargetBindingService,
    private encryptionService: EncryptionService,
    private apiBotService: ApiBotService
  ) {}

  @PostMethod()
  @Permissions(Permission.CreateTargets)
  async create(@Body() targetDto: CreateBitvavoTargetDto, @User() user: UserClass) {
    const userTargets = await this.repository.getAll(user.sub);
    const safeModel = {
      ...targetDto,
      name: targetDto.name ? targetDto.name : `Bitvavo Wallet ${userTargets.length + 1}`,
      key: this.encryptionService.encrypt(targetDto.key),
      secret: this.encryptionService.encrypt(targetDto.secret)
    };
    await this.repository.create({...safeModel, userId: user.sub, positions: []}); // TODO some unique checking stuff
  }

  @GetMethod()
  @Permissions(Permission.ReadTargets)
  async get(@User() user: UserClass) {
    if (user.permissions.includes(Permission.AdminTargets)) {
      return await this.repository.getAllInternal();
    }
    return await this.repository.getAll(user.sub);
  }

  @GetMethod("/:id")
  @Permissions(Permission.ReadTargets)
  async getOne(@Param("id") targetId: string, @User() user: UserClass): Promise<BitvavoSingleTargetResponse> {
    let targetOpt;
    if (user.permissions.includes(Permission.AdminTargets)) {
      targetOpt = await this.bitvavoService.getOneInternal(targetId);
    } else {
      targetOpt = await this.bitvavoService.getOne(targetId, user.sub);
    }
    if (!targetOpt) {
      throw new NotFoundException();
    }
    const {bindings, target} = targetOpt;

    const decryptedKey = this.encryptionService.decrypt(target.key);
    const decryptedSecret = this.encryptionService.decrypt(target.secret);
    const balances = await getBalances(target, decryptedKey, decryptedSecret);

    return {
      target: toTargetDto({type: CollectionNames.Bitvavo, name: target.name, _id: target._id, targetMode: target.targetMode}),
      // producer: mapProducerToDto(producer),
      balances: balances,
      bindings: bindings
    };
  }

  @PostMethod("/:id/placeOrder")
  async placeOrder(@Param("id") id: string, @Body() body: BitvavoPlaceOrderDto, @User() user: UserClass): Promise<BitvavoOrderResponse> {
    let target;
    if (user.permissions.includes(Permission.AdminTargets)) {
      target = await this.repository.getOneByIdInternal(id);
    } else {
      target = await this.repository.getOneById(id, user.sub);
    }
    if (!target) {
      throw new NotFoundException();
    }
    return await this.bitvavoService.handleSignal(target, body);
  }

  @Patch("/:id")
  @Permissions(Permission.EditTargets)
  async update(@Param("id") id: string, @User() user: UserClass, @Body() targetDto: UpdateBitvavoTargetDto) {
    let target;
    let key;
    let secret;
    if (user.permissions.includes(Permission.AdminTargets)) {
      target = await this.repository.getOneModelByIdInternal(id);
    } else {
      target = await this.repository.getOneModelById(id, user.sub);
    }
    if (!target) {
      throw new NotFoundException();
    }
    if (targetDto.key) {
      key = this.encryptionService.encrypt(targetDto.key);
    } else {
      key = target.key;
    }
    if (targetDto.secret) {
      secret = this.encryptionService.encrypt(targetDto.secret);
    } else {
      secret = target.secret;
    }
    Object.assign(target, {...targetDto, key, secret});
    await target.save();
  }

  @DeleteMethod("/:id")
  @Permissions(Permission.DeleteTargets)
  async deleteTarget(@Param("id") id: string, @User() user: UserClass) {
    let target;
    if (user.permissions.includes(Permission.AdminTargets)) {
      target = await this.repository.getOneModelByIdInternal(id);
    } else {
      target = await this.repository.getOneModelById(id, user.sub);
    }
    if (!target) {
      throw new NotFoundException();
    }
    await this.repository.deleteById(id);
    await this.producerTargetBindingService.deleteAllForTarget({id: target.id, type: CollectionNames.Bitvavo});
  }

  @PostMethod("/:id/sellto/:base")
  @Permissions(Permission.EditTargets)
  async sellAllForTarget(@Param("id") id: string, @Param("base") base: string, @User() user: UserClass) {
    let target;
    if (user.permissions.includes(Permission.AdminTargets)) {
      target = await this.repository.getOneModelByIdInternal(id);
    } else {
      target = await this.repository.getOneModelById(id, user.sub);
    }
    if (!target) {
      throw new NotFoundException();
    }
    await this.producerTargetBindingService.deleteAllForTarget({id: target.id, type: CollectionNames.Bitvavo});
    await this.bitvavoService.sellAllToAsset(target, base);
  }

  @PatchMethod("/:id/changeTargetMode")
  @Permissions(Permission.EditTargets)
  async changeTargetMode(@Param("id") id: string, @Body() targetDto: ChangeBitvavoTargetMode, @User() user: UserClass) {
    let target;
    if (user.permissions.includes(Permission.AdminTargets)) {
      target = await this.repository.getOneModelByIdInternal(id);
    } else {
      target = await this.repository.getOneModelById(id, user.sub);
    }
    if (!target) {
      throw new NotFoundException();
    }

    Object.assign(target, {...target, targetMode: targetDto.targetMode});
    await target.save();
  }

  @PostMethod("/:id/stopBot/:base")
  @Permissions(Permission.EditTargets)
  async sellSingleTarget(@Param("id") id: string, @Param("base") base: string, @Body() body: SellSingleBot, @User() user: UserClass) {
    let target;
    let producer;

    if (user.permissions.includes(Permission.AdminTargets)) {
      target = await this.repository.getOneModelByIdInternal(id);
    } else {
      target = await this.repository.getOneModelById(id, user.sub);
    }

    producer = await this.apiBotService.getOneModelInternal(body.botName);

    if (!target || !producer) {
      throw new NotFoundException();
    }

    await this.producerTargetBindingService.deleteSingleForTarget(
      {id: target.id, type: CollectionNames.Bitvavo},
      {id: producer._id, type: CollectionNames.ApiBot}
    );
    await this.bitvavoService.sellAllToAsset(target, base);
  }
}

export const createBitvavoClient = (key: string, secret: string) => {
  return bitvavo().options({
    APIKEY: key,
    APISECRET: secret,
    ACCESSWINDOW: 10000,
    RESTURL: "https://api.bitvavo.com/v2",
    WSURL: "wss://ws.bitvavo.com/v2/",
    DEBUGGING: false
  });
};

const balanceToDto = (balance: {symbol: string; available: string; inOrder: string}): BitvavoBalanceDto => {
  return balance as BitvavoBalanceDto;
};

Here is my controller.spec.ts

import {BitvavoService} from "./bitvavo.service";
import {Test} from "@nestjs/testing";
import {BitvavoController} from "./bitvavo.controller";

describe("Bitvavo Controller", () => {
  let controller: BitvavoController;

  const mockValue = {};

  beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({
      controllers: [BitvavoController],
      providers: [BitvavoService]
    })
      .overrideProvider(BitvavoService)
      .useValue({onModuleInit: jest.fn(), handleSignal: jest.fn(), sellAllToAsset: jest.fn(), getOne: jest.fn(), getOneInternal: jest.fn()})
      .compile();
  });

  it("test", () => {});
});

Get current user level without using while loops?

In my messaging app, I have a level system that track’s a user’s activeness with XP. It doesn’t store the actual level, only the amount of XP they have. Here’s the function for calculating the level:

function calculateLevel(num) {
  var lv = 0;
  do {
    lv++;
  } while (num >= Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv)))));
  var x = num-Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv-1))));
  var left = Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv))))-num;
  var thislv = x + left;
  return {
    level: lv,
    xp: x,
    left: left,
    next: Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv)))),
    prev: Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv-1)))),
    thislv: thislv+1
  };
}

The formula for calculating how much XP each level requires is 30√(√(level)). However, I don’t want to use a while loop, because the app starts to slow down a bit after level 60. Is there a way to get the current level without having to use loops?

get value in input field from virtual keyboard in react

I am working on a countdown watch which have a virtual numpad (given in code as button) and three input (hour,minute and second). now i want that whenever i click input box and type in virtual numpad ,it print the value in that box only.

  1. there i used three ref to getElement of input and change set their value but dont know how to set for specific box
const inputOne = useRef(null);
const inputTwo = useRef(null);
const inputThree = useRef(null);

  const changeValue = (val) => {
    inputOne.current.value  = setTime({hour: updatedHour + val, minute: updatedMinute, second: updatedSecond}); 
    inputTwo.current.value = setTime({hour: updatedHour, minute: updatedMinute + val, second: updatedSecond});
    inputThree.current.value = setTime({hour: updatedHour, minute: updatedMinute, second: updatedSecond + val}); 
    }

const changeTime = (e) => {
    setTime({ ...time, [e.target.name]: e.target.value });
  };
  1. this is input fields i use , updatedHour,updatedMinute and updatedSecond is part of setTime state.
  <input ref={props.inputOne} onChange={props.changeTime} name="hour"  placeholder="Hour"  value={props.updatedHour} />
          <input ref={props.inputTwo} onChange={props.changeTime} name="minute"  placeholder="Minute" value={props.updatedMinute} />
          <input ref={props.inputThree} onChange={props.changeTime} name="second"  placeholder="Second" value={props.updatedSecond} />
  1. this is buttons which create virtual keyboard
 <button className="grid-item" tpye='button' onClick={()=> props.changeValue('1')}>1</button>
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('2')}>2</button>
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('3')}>3</button>  
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('4')}>4</button>
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('5')}>5</button>
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('6')}>6</button>  
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('7')}>7</button>
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('8')}>8</button>
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('9')}>9</button>  
  <button className="grid-item" tpye='button' >Prev</button>  
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('0')}>0</button>  
  <button className="grid-item" tpye='button' >Next</button>  

Highlight an individual character of text block containing links and heading on mouse hover

I am trying to achieve that when hover over a character, the character should change its color. It should work on individual character , links, heading etc.

My following code gives me result that i want but it removes the links and headings.

JS Fiddle: http://jsfiddle.net/bvpodc6z/1/

HTML CODE

<div class="words">
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
        sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
        sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
        <a href="#link">LINK</a>
        <h1>
        Heading
        </h1>
        Stet clita kasd gubergren, no sea takimata sanctus e Lorem ipsum dolor sit amet.
    </div>

JS Code

$cont = $('.words');
parts = $.map($cont.text().split(''), function(v){
    return $('<span />', {text:v});
});
$cont.empty().append(parts);

CSS Code

.words span:hover{color:#F00}