Categories
JavaScript Answers

How to Pass Additional Data via Custom Events in JavaScript?

To pass additional data via custom events in JavaScript, we can pass an object into the CustomEvent constructor.

For instance, we can write:

window.addEventListener("MyEvent", (evt) => {
  console.log(evt.detail);
});

const evt = new CustomEvent("MyEvent", {
  detail: "Any Object Here"
});
window.dispatchEvent(evt);

to listen to the MyEvent event with the window.addEventListener method.

In the event handler, we log the value of the evt.detail property, which will be set when we pass in an object into the CustomEvent constructor’s 2nd argument with the detail property.

The first argument of the CustomEvent constructor is the event name.

Finally, we call window.dispatchEvent with the evt object to emit the event.

Therefore, we should see 'Any Object Here' logged from the event handler.

Categories
JavaScript Answers jQuery

How to Determine the Pixel Length of a String in JavaScript and jQuery?

To determine the pixel length of a string in JavaScript and jQuery, we can put the string in a span and then use the jQuery width method to determine the width of the span.

For instance, we can write the following HTML:

<span></span>

Then we can write:

const span = document.querySelector('span')  
span.innerText = 'Here is my string'  
console.log($(span).width())

to get the span width document.querySelector .

And then we set innerText to the string of the span.

Finally, we log the span’s width that we get from $(span).width() from jQuery.

The console log should log 111.

Categories
JavaScript Answers

How to Remove Zero-Width Space Characters from a JavaScript String?

To remove zero-width space characters from a JavaScript string, we can use the JavaScript string replace method that matches all zero-width characters and replace them with empty strings.

Zero-width characters in Unicode includes:

  • U+200B zero width space
  • U+200C zero-width non-joiner Unicode code point
  • U+200D zero width joiner Unicode code point
  • U+FEFF zero-width no-break space Unicode code point

For instance, we can do the replacement by writing:

const userInput = 'au200Bbu200Ccu200DduFEFFe';
console.log(userInput.length);
const result = userInput.replace(/[\u200B-\u200D\uFEFF]/g, ”);
console.log(result.length);

We have the userInput string that has the zero-width characters listed.

From the first console log, we see userInput.length is 9.

Then we call replace with a regex that matches the zero-width characters listed and replaces them all with empty strings.

And so we see that result.length is 5, so the zero-width characters were removed.

Categories
JavaScript Answers

How to Fetch an Array of URLs with the Promise.all Method?

To fetch an array of URLs with the Promise.all method, we can call map to map an array of URLs to promises that fetch the data from the URLs.

Then we can call Promise.all on the array of promises.

For instance, we can write:

const fetchAll = async (urls) => {
  const res = await Promise.all(urls.map(u => fetch(u)))
  const jsons = await Promise.all(res.map(r => r.json()))
  console.log(jsons)
}

const urls = [
  'https://yesno.wtf/api',
  'https://yesno.wtf/api',
  'https://yesno.wtf/api'
]
fetchAll(urls)

to create the fetchAll function that takes an array of urls .

Then we call urls.map with a callback that returns promises returned by fetch for the URL u .

Then we call Promise.all on the array to return a promise with an array of response objects and assign it to res .

Next, we call res.map with a callback that return the JSON response object with the r.json method.

And then we call Promise.all on that to return a promise with the response JSON objects.

Therefore, jsons is something like:

[
  {
    "answer": "yes",
    "forced": false,
    "image": "https://yesno.wtf/assets/yes/10-271c872c91cd72c1e38e72d2f8eda676.gif"
  },
  {
    "answer": "yes",
    "forced": false,
    "image": "https://yesno.wtf/assets/yes/11-a23cbde4ae018bbda812d2d8b2b8fc6c.gif"
  },
  {
    "answer": "yes",
    "forced": false,
    "image": "https://yesno.wtf/assets/yes/0-c44a7789d54cbdcad867fb7845ff03ae.gif"
  }
]

since we called with 3 URL strings in the urls array.

Categories
JavaScript Answers jQuery

How to Get All HTML Element IDs with jQuery?

To get all HTML element IDs with jQuery, we just have to select all the elements and then we can get the id property from each element.

For instance, if we have the following HTML:

<div id="mydiv">
  <span id='span1'></span>
  <span id='span2'></span>
</div>

Then we can get the IDs of all the span elements by writing:

const ids = [...$("#mydiv").find("span")].map(s => s.id);
console.log(ids)

We get all the spans with:

$("#mydiv").find("span")

Then we convert the returned nodelist into an array with the spread operator.

And then we call the JavaScript array map method it the returned array with a callback that returns the id from the s span element.

Therefore ids is [“span1”, “span2”] .