Categories
JavaScript Answers

How to Remove Part of a String Before a “:” in JavaScript?

One way to remove part of a string before a colon is to use the JavaScript string’s substring method.

For instance, we can write:

const str = "Abc: Lorem ipsum sit amet";
const newStr = str.substring(str.indexOf(":") + 1);
console.log(newStr)

We use the indexOf method to get the index of the first colon.

Then we add 1 to that pass that into substring to get the substring after the first colon.

Therefore, newStr is 'Lorem ipsum sit amet’ .

Use the Array.prototype.split and Array.prototype.pop Methods

Another way to remove the part of a string before the colon is to use the JavaScript array’s split and pop methods.

To do this, we write:

const str = "Abc: Lorem ipsum sit amet";
const newStr =  str.split(":").pop();
console.log(newStr)

We call split on str to split str into an array using the colon as the delimiter.

Then we call pop to return the last element of the array returned by split .

And so we get the same result as before.

Use a Regex

We can also use a regex to split a string by a given delimiter and get the part we want from the split string.

For instance, we can write:

const str = "Abc: Lorem ipsum sit amet";
const newStr = /:(.+)/.exec(str)[1];
console.log(newStr)

to call exec on the regex that matches the colon separator.

And we use index 1 to get the 2nd item from the split string.

And so we get the same result as before.

Categories
JavaScript Answers

How to Download Data From a URL with JavaScript?

We can create an invisible link and click it with JavaScript to download a file.

To do this, we write:

const downloadURI = (uri, name) => {
  const link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
downloadURI('https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.doc', 'sample.doc')

We have the downloadURI function that takes the uri of the file to download and the name of the file that’s downloaded.

In the function body, we create an a element with the document.createElement method.

Then we set the download attribute with:

link.download = name;

to set the filename of the downloaded file to name .

Next, we set the href attribute with:

link.href = uri;

Then we call appendChild to append the link to the body element.

And then we click on the link by calling click .

And finally, we call removeChild to remove the link from the body.

Now when we run the downloadURI function, files should be downloaded if it can’t be opened by the browser directly.

Categories
JavaScript Answers

How to Check All Checkboxes Using jQuery?

Sometimes, we want to check all checkboxes with jQuery.

In this article, we’ll look at how to check all checkboxes with jQuery.

Set the checked Property

We can use jQuery to set the checked attribute of each checkbox element.

For instance, if we have the following HTML:

<div>  
  <input type="checkbox" id="checkAll">check all  
  <input type='checkbox' value='apple'> apple  
  <input type='checkbox' value='orange'> orange  
  <input type='checkbox' value='grape'> grape  
</div>

Then we can write the following JavaScript code to check all the checkboxes when we click check all:

$("#checkAll").click(function() {  
  $('input:checkbox').prop('checked', this.checked);  
});

We get the checkbox with ID checkAll and add a click listener to it with click .

Then in the click handler callback, we get all the checkboxes and set the checked attribute of each of them to the checked value of the checkbox with ID checkAll .

Therefore, when we click check all, they’ll all be checked on and off at the same time.

Conclusion

We can use jQuery to set the checked attribute of each checkbox element.

Categories
JavaScript Answers

How to Make an Anchor Link Go Some Pixels Above Where it’s Linked To with JavaScript?

We can use the window.scrollTo method to scroll to the coordinates we want on the page when we click on a link with a hash as the href .

For instance, we can write the following HTML:

<a href='#'>link 1</a>
<a href='#foo'>link 2</a>
<a href='#bar'>link 3</a>

<div id='bar' style='height: 500px'>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>

<div id='foo' style='height: 500px'>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>

Then we write:

const offsetAnchor = () => {
  if (location.hash.length !== 0) {
    window.scrollTo(window.scrollX, window.scrollY - 100);
  }
}

const anchors = document.querySelectorAll('a[href^="#"]')

for (const a of anchors) {
  a.addEventListener('click', (event) => {
    window.setTimeout(() => {
      offsetAnchor();
    }, 0);
  });
}

document.addEventListener('click', (event) => {
  window.setTimeout(() => {
    offsetAnchor();
  }, 0);
});

window.setTimeout(offsetAnchor, 0);

We have the offsetAnchor function that checks if the hash is appended to the URL with location.hash.length .

If it exists, then we scroll to the location of the element with the ID given by the hash, but with the y coordinate subtracted by 100.

Next, we get the a elements with href starting with the pound sign.

And if the for-of loop, we call addEventListener to add a click handler to each a element.

In the click handler, we call offsetAnchor in the setTimeout callback.

We put it in the setTimeout callback so that it’ll be called after the scrolling is done.

Next, we do the same with document so we scroll 100 pixels up from where we click on the page.

Also, we call offsetAnchor initially to scroll to the initial coordinates of the page.

Categories
JavaScript Answers

How to Add an Event listener for When an Element Becomes Visible with JavaScript?

We can use the IntersectionObserver API to watch when an element is visible or not.

For instance, if we have the following HTML:

<div>

</div>

Then we can add the following JavaScript:

const div = document.querySelector('div')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  p.id = `el-${i}`
  div.appendChild(p)
}

const options = {
  rootMargin: '0px',
  threshold: 1.0
};

const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    console.log(entry.intersectionRatio > 0 ? 'visible' : 'invisible');
  });
}, options);

const element = document.querySelector('#el-50')
observer.observe(element);

to add elements into the div with the for loop.

Then we use the IntersectionObserver constructor to add the intersection observer.

The options object has the rootMargin which is the margin for when the element is considered to be visible.

threshold is how much of the element is visible on the screen for it to be considered visible.

This value is between 0 and 1.

We pass in a callback into IntersectionObserver which runs when the element we’re watching appears or disappears from the screen.

We loop through entries to get the intersection entries object.

And we log entry.intersectionRatio and check if it’s bigger than 0 to see if the element we’re watching is visible.

Finally, we call observer.observe to watch the element with ID el-50 to be visible or invisible on the screen.