Categories
JavaScript Answers

How to Test if a URL String is Absolute or Relative with JavaScript?

To test if a URL string is absolute or relative with JavaScript, we can use a regex to do the check.

For instance, we can write:

const r = new RegExp('^(?:[a-z]+:)?//', 'i');
console.log(r.test('http://example.com'));
console.log(r.test('HTTP://EXAMPLE.COM'));
console.log(r.test('ftp://example.com/file.txt'));
console.log(r.test('//cdn.example.com/lib.js'));
console.log(r.test('test'));

We create the regex with the ^(?:[a-z]+:)?//’ pattern to check if the URL starts something with :// after it and more path segments appended after that.

The part before :// is optional for a URL to be considered absolute.

Then we use the test method to check if each URL is absolute or relative.

If it’s absolute, test returns true . Otherwise, it returns false .

Therefore, the first 4 console logs logs true and the last one logs false .

Categories
JavaScript Answers

How to Display a Loading Indicator When Making an Ajax Request with jQuery?

To display a loading indicator when making an Ajax request with jQuery, we can use the ajaxSetup method to show and hide the loading indicator before the request starts and when it finishes respectively.

For instance, we can add the loading indicator by writing:

<div id='loading'>
  loading
</div>

Then we can call the ajaxSetup method and then make the request by writing:

$.ajaxSetup({
  beforeSend: () => {
    $("#loading").show();
  },
  complete: () => {
    $("#loading").hide();
  }
});

$.ajax({
  type: 'GET',
  url: 'https://yesno.wtf/api',
})

We call ajaxSetup to add code that runs with all Ajax request made with ajax unless we specify otherwise.

beforeSend is run before the request is made, so we call $(“#loading”).show(); to show the loading indicator.

complete is run before the request is made, so we call $(“#loading”).hide(); to hide the loading indicator.

Then when we call ajax to make the Ajax request, we see the loading indicator shown and then hidden.

Categories
JavaScript Answers

How to Tell setInterval to Only Fire x Amount of Times with JavaScript?

To tell setInterval to only fire x amount of times with JavaScript, we can keep track of the number of times the setInterval callback is called.

Then when the limit is reached, we can call clearInterval to stop the setInterval timer.

For instance, we can write:

let x = 0;  
const intervalID = setInterval(() => {  
  if (++x === 5) {  
    window.clearInterval(intervalID);  
  }  
  console.log('hello')  
}, 200);

to keep track of the number of times the setInterval callback is called with x .

Then we call setInterval with a callback that increments x with ++ in front to return the value of x after incrementing by 1.

Next, we check if x is 5 to top the timer with clearInterval when the setInterval callback has been called 5 times.

clearInterval is called with the intervalID to stop the timer.

And then we call console log to log some message.

200 is the number of milliseconds between each setInterval call.

As a result, the setInterval callback will be called 5 times only.

Categories
JavaScript Answers

How to Disable the Submit Button on Form Submission with JavaScript and jQuery?

To disable submit button on form submission with JavaScript and jQuery, we can listen to the submit event of the form.

Then we can set the disabled attribute of the submit button to true when we submit the form.

For instance, if we have the following HTML form:

<form>
  <input>
  <input type='submit'>
</form>

Then we can write the following JavaScript to disable the submit button when we submit the form with jQuery by writing:

$('form').submit(function() {
  $(this).find(':input[type=submit]').prop('disabled', true);
});

We get the form with $(‘form’) .

Then we call submit on it with a callback to listen to the submit event of the form.

The callback we pass into submit get the submit button of the form with $(this).find(‘:input[type=submit]’) .

Then we call prop with 'disabled' and true to disable the form’s submit button.

Categories
JavaScript Answers

How to Detect if an HTML5 Video Element is Playing with JavaScript?

To detect if an HTML5 video element is playing with JavaScript, we can listen to various events emitted by the HTML5 video element.

To do this, we can add the video element with the following HTML:

<div id="output"></div>
<video id="myVideo" width="320" height="176" controls autoplay>
  <source src="https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4" type="video/mp4">
</video>

to add a div to show some text when various events are triggered.

Then we add a video element with the video.

Next, we add the following JavaScript code to listen to video player events and set the div content according to the event triggered:

const media = document.getElementById('myVideo');
const output = document.getElementById('output');

media.addEventListener("playing", () => {
  output.innerHTML = "Playing event triggered";
});

media.addEventListener("pause", () => {
  output.innerHTML = "Pause event triggered";
});

media.addEventListener("seeking", () => {
  output.innerHTML = "Seeking event triggered";
});

media.addEventListener("volumechange", () => {
  output.innerHTML = "Volumechange event triggered";
});

We get the video and div elements with document.getElementById .

Then we call addEventListener on the video player to listen to various events emitted by it.

The 'playing' event is emitted when the video is playing.

The 'pause' event is emitted when the video is paused.

The 'seeking' event is emitted when we’re moving the seek bar.

The 'volumechange' event is emitted when the video volume is changed.

In the event handlers, we set the innerHTML of the div to the content we want to display.