Tag Archive for: JavaScript


JavaScript offers a variety of functionalities to create interactive interfaces. One can retrieve the value of any element using JavaScript methods. The input value can be printed somewhere on the web page or it can be obtained as an alert message. All this is possible with the help of JavaScript. Here, we will describe the JavaScript support to get the input value from any element. The following learning outcomes are expected:

How to Get Input Value in JavaScript

JavaScript provides two properties to get the input values by employing the getElementById, getElementsByClassName, and querySelector methods. These methods extract the string as well as the numerical value to display the user information. All the famous browsers support both of these properties. The value property returns the information of the user. Moreover, the property is useful for assigning any specific value for display in the browser window.

The syntax of these methods is stated below.

Syntax of getElementById

document.getElementById(«textId»).value = «text_message»;

Syntax of getElementsByClassName

document.getElementsByClassName(«clName»).value ;

Syntax of querySelector

document.querySelector(«id1»).value

The description of the above parameters is as below:

  • textId: denotes the id of an element.
  • text_message: represents the message to be displayed.
  • clName: specify the name of the class.
  • Id1: represents the id or class of an HTML element.

Example 1: Get the Input Value Using the getElementbyId() Method

Another example is considered for getting the input value in JavaScript.

HTML

<!DOCTYPE html>
<html>
<body>
<center>
<h2> An example to get the value of the text field</h2>
Favorite Message: <input type=«text» id=«mtxt» value=«Welcome to JavaScript»>
<p>Press button to display the text value.</p>
<button onclick=«Display_fn()»>Display Button</button>
<p id=«demo»></p>
</center>
</body>
</html>
<script src=«test.js»> </script>

The HTML code gets the input value “Welcome to JavaScript” by pressing the “Display Button”. The button is attached with the Display_fn() method.

JavaScript

function Display_fn() {
  var a = document.getElementById(«mtxt»).value;
  document.getElementById(«demo»).innerHTML = a;
}

A method Display_fn() is employed to retrieve the value of text in the HTML file by getElementById.

Example 2: Get the Input Value Using the getElementsbyClassName() Method

An example is considered to get the numeric value from the input field in JavaScript.

HTML file

<!DOCTYPE html>
<html>
<body>
<center>
    <h2> An example to get the numeric value of field</h2>
    <input type=«text» placeholder=«Type « id=«inp_id1» class=«inpCls»>
    <br> </br>
    <button type=«button» onclick=«getInpVal();»>Get Numeric Value</button>
</center>
</body>
</html>
<script src=«test.js»> </script>

In this code, the description is as below:

  • The class inpCls is used to input the numeric number.
  • After that, a button is attached that is associated with the getInpVal() method.
  • In the end, a JavaScript file test.js is linked by assigning the source src variable.

JavaScript

function getInpVal() {
  let inpVal = document.getElementsByClassName(«inpCls»)[0].value;
  alert(inpVal);}

In the JavaScript file:

  • A method getInpVal() is used to extract the value from the HTML file.
  • The extraction is performed by getElementByClassName(“inpCls”)[0].value.
  • In the end, an alert message is generated by passing the inpVal variable.

Output

The output shows that the user first inputs any number. After that, an alert box is generated by pressing the “Get Numerical Value” button.

Example 3: Get Input Value Using querySelector() Method

Another example is considered to get the value using the querySelector() method.

Code

<html>
<body>
   <h2>Get value using Query Selector <br></h2>
 <input type=«text» id=«id1» > <br><button type=«button»  onclick=«getValueInput()»>
    Display Button
  </button>
  <p id=«val»></p>
  <script>
    const getValueInput = () =>{
      let val1 = document.querySelector(«#id1»).value;
      document.querySelector(«#val»).innerHTML = `Message: ${val1}`;
    }
  </script>
</body></html>

In this code, the description is as follows:

  • Firstly, a text box and a button are attached with <input> and <button> tags respectively.
  • The button is associated with the getValueInput() method.
  • In this method, querySelector() is employed to extract the value of the text box and display it using val1.

Output

The output shows the message “JavaScript” by pressing the button in the browser.

Conclusion

The getElementById, getElementsByClassName, and querySelector() methods are utilized to get the input value in JavaScript. The first two methods retrieve the elements using the id and class name. While the third method can get the elements using an id as well as a class name. Here, you have learned to use all three of these methods to get input values in JavaScript.



Source link



There are multiple ways of writing a program that selects a random element from an Array, but the best-suited method is to use a combination of Math.random() and Math.floor() methods. Math.random() method provides the user with a random floating-point value between 0 and 1. While the Math.floor() method simply takes in a floating-point value and rounds down the value to make it an integer.

Method 1: Random element from an Array Using Math.random() & Math.floor()

First, create an array with the following line:

my_arr = [«Paris», «London», «Bangkok», «New York», «Los Angeles», «Dubai»];

This array represents a list of cities to choose from at random. After this, simply create a new function that takes in the array as a parameter like:

function elemenet_Selector(arr) {
 
}

Within this function, the very first thing is to get the length of the array passed to it inside a separate variable:

array_length = arr.length;

Then, simply call the Math.random() method to get a floating-point value and then multiply that number with the length of the array to get the range between 0 and array length:

value = Math.random() * array_length;

This line will return floating point values, but they are no good when it comes to being the index of an array. Confirm this by simply wrapping this line into the console log and observing the output:

The output on the terminal is as:

To change these values into an integer, simply pass the value variable into the Math.floor() method and remove the console.log(value) line:

indexValue = Math.floor(value)

At the end of the function, use a return statement and return the element at the indexValue of the array:

After that, come out of the function element_Selector, and make a call to this function and wrap that call inside a console log function to print out the randomly selected element:

console.log(elemenet_Selector(my_arr));

The complete code snippet is as:

my_arr = [«Paris», «London», «Bangkok», «New York», «Los Angeles», «Dubai»];

function elemenet_Selector(arr) {
  array_length = arr.length;
  value = Math.random() * array_length;
  indexValue = Math.floor(value);
  return arr[indexValue];
}

console.log(elemenet_Selector(my_arr));

Execute this program and observe the following result:

It is clear from the output that random elements are selected from the array.

Method 2: Using Double NOT Bitwise Operator

Start by creating an array just like in method 1 with the help of the following line:

my_arr = [«Paris», «London», «Bangkok», «New York», «Los Angeles», «Dubai»];

Afterwards, call Math.random() and multiple it with the length of our array to get a range from 0 to the length:

value = Math.random() * my_arr.length;

This time around, to convert this value into an integer representing the index of the array, simply apply the double NOT Bitwise operator, which is the double tilde operator (~~), and fetch the value from the array as:

var item = my_arr[~~value];

Last, simply print out the randomly selected element onto the terminal with the help of console log function:

Complete code snippet for method 2 is as:

my_arr = [«Paris», «London», «Bangkok», «New York», «Los Angeles», «Dubai»];
value = Math.random() * my_arr.length;
var item = my_arr[~~value];
console.log(item);

Execute this program and observe the following result:

It is clear from the output that a random element is being selected from the array

Conclusion

In JavaScript, we can utilize the Math.random() function with either the Math.floor() function or the double NOT Bitwise operator to fetch a random item from an array. Math.random(), when multiplied by the length of the array, provides a range value of index between zero and the array’s length. However, this range value is in floating point, therefore, use Math.floor() or NOT Bitwise operators to convert it into an integer to be used as the array index. This article has explained both of these methods along with an example



Source link



There are multiple ways of storing key => value arrays in JavaScript. However, the tricky part is storing the keys and values from two different arrays into a single element. And to add to its trickiness, key and value are to be stored in such a scheme that fetching a key with its respective value is easy. This cuts down the number of methods to achieve the task at hand to only two. The two most promising methods include the use of Objects and Maps. This article will go through both of these methods one by one.

Note: This article will assume that keys and values are stored in different arrays, and the objective is to store them together and have them formatted as “key => value” while fetching.

Method 1: Using Objects to Store Key => Value Arrays

To demonstrate this method, first create a key array and a value array with the following lines:

var keysArray = [«China», «England», «Egypt», «Finland», «Greece»];
var valuesArray = [«Beijing», «London», «Cairo», «Helsinki», «Athens»];

After that, create an empty JavaScript object with the following line:

After that, simply copy the keys and values from their array and add them in the object using the following lines:

for (var i = 0; i < keysArray.length; i++) {
  resultObj[keysArray[i]] = valuesArray[i];
}

In this above code snippet:

  • A for loop is run and its iterations are equal to the number of elements inside the keys array.
  • In each iteration, a new attribute of property of the object is created, and it is given the name equal to the element inside the key array and its respective value from the value array by using the same index values.

After that, pass the resultObj to the console log function to print it out on the terminal:

Executing the code will provide the following output:

The keys and values are stored together, but they are still not in the “key => format
To display them in the correct format, use the following lines of code:

for (x of Object.keys(resultObj)) {
  console.log(x + » => « + resultObj[x]);
}

In this code snippet:

  • Object.keys() method returns the keys of the object in its argument one by one. The keys are getting stored inside the variable “x
  • String concatenation is used to format the output of the console log as “keys=> values”

Executing the program now produces the following result:

The output shows that the keys are not only stored together but also formatted in the correct way.

Method 2: Using Maps to Store Key => Value Arrays

To demonstrate the usage of maps for storing keys and their respective values, create two arrays with keys and values with the following lines of code:

var keysArray = [«China», «England», «Egypt», «Finland», «Greece»];
var valuesArray = [«Beijing», «London», «Cairo», «Helsinki», «Athens»];

The next step is to create a map, for this create a variable and set it equal to the new Map() constructor like:

To add values to a Map variable, there is this method mapVar.set(). Use this function to add keys and their respective values:

for (i = 0; i < keysArray.length; i++) {
  resultMap.set(keysArray[i], valuesArray[i]);
}

In the code snippet mentioned above:

  • A for loop is used to iterate through the keysArray and the valuesArray using the length of the keysArray.
  • In each iteration, resultMap.set() method is used to store the key and value pair in the map.

After this, simply pass the resultMap variable onto the terminal by using the console log function:

This code will produce the following output:

It is sort of in the right format, but it includes a little extra information. To correctly format it, use the following lines:

for (key of resultMap.keys()) {
  console.log(key + » => « + resultMap.get(key));
}

In this code snippet:

  • resultMap.keys() method returns the keys of the map one by one to the key variable.
  • resultMap.get() method is used to get the value of a specific key.
  • And in the console log function, string concatenation is used to correctly format the output.

Executing the code now produces the following output on the terminal:

The output shows that the keys are not only stored together but also formatted in the correct way.

Conclusion

In JavaScript, Objects and Maps are the two elements that are most suited to store keys and value pairs, even if the task at hand is to take keys and values from individual arrays and place them inside a single entity. Afterward, whenever the user is trying to get keys and their respective values, they can be easily formatted in “key => value” format by using simple string concatenation in JavaScript.



Source link


The Array.isArray() was released with the release of ECMAScript5 JavaScript. This method simply checks whether the argument passed to its arguments is an array or not. This article will explain this Array isArray() method by explaining its syntax and then showcasing some examples.

We will start by going over the syntax of the Array isArray() method.

Syntax
Observe the syntax of the Array isArray() below:

In this syntax:

  • Array is the default JavaScript Array Object
  • Object is the argument, the one we want to determine as an array or not

Return Type

  • Boolean: Returns true if the object passed to this method was actually an array otherwise it would return false

Additional Information

Since this is a method of the default JavaScript Array Object, therefore it is also known as the static property of this Array Object.

Example 1: Passing an Array to Array.isArray() Method

To demonstrate the working of this method, first create an array of the same types of values with the help of the following line:

my_object = [1, 2, 3, 4, 5, 6, 7, 8, 9];

After that, pass this array to the Array.isArray() method and store the return value in a new variable named as the result:

result = Array.isArray(my_object);

After that, simply display the value inside the result variable on the terminal using the console log function:

Execute the code, and observe the output to be:

The output shows that the object passed to this method was actually an array.

Example 2: Passing an Array With Different Data Type Values

To check whether this method works with an array containing values of different data types, create an array using the following line:

my_object = [1, 2, «Google», 4, true, 6, «7», 8.673, 9];

Pass this object into the Array.isArray() method and store the result in a result variable:

result = Array.isArray(my_object);

Afterwards, simply print the result from the result variable onto the terminal using the console log() function:

Execute the code and observe the following output:

From the output, it is conclusive that the type of data stored inside the array doesn’t matter. It only checks whether the object is an array or not, which in this case was true.

Example 3: Passing a String Object in Array.isArray() Method

To demonstrate what happens when a non-array object is passed to the Array isArray() method, create a new string variable with the help of the following line:

string_var = «Hello World»;

Pass this string value into the arguments of the Array.isArray() method and store the outcome in a new variable:

result_var = Array.isArray(string_var);

Print the value inside the result_var on the terminal using the console log() function:

Execute the program and get the following output on the terminal:

It returns that the object passed into its argument was not an array.

Conclusion

The Array.isArray() method is pretty simple. It simply checks whether the object in its argument is an array or not and returns true or false to the caller. If an array is being passed, the values or even the data types of its values don’t matter. In this article, we have learned about the different outcomes of the Array.isArray() method with the help of different examples.



Source link



There are numerous different ways of disabling the back button or at least messing with the working of the back button so that the browsers cannot go to the previous page. However, fully disabling the browser’s back button is not a good option, plus client-side applications don’t have that many privileges or rights to do so due to security reasons.

In this article, we will implement a simple logic through JavaScript, which stops the browsers from going to the previous page using the window object.

The window.history.forward() Method

In this article, we will stop the habitual working of the back button of the web browser by using the window Object. And to be precise, we will head inside the window object’s history and move it “forward” when the browser tries to revisit the previous page.

Demonstration of Window.history.forward() Method

To start, we need two different HTML pages. The first page is called the home.html, and it contains the following lines:

<center>
      <a href=«secondPage.html»>Click me to visit the next page</a>
</center>

As you can see, we are simply creating an <a> in which we are simply referring to the secondPage.html.

After that, simply create the second HTML with the exact name secondPage.html. And in this HTML document, you want to add the following lines:

<center>
  <b>This is the second page</b>
</center>

This second page only contains text that tells the user that this is the second page. Running the home webpage will give the following result on the browser:

As you can see, clicking the link takes us to the second page, and from the second page, you can press the back button to again come to the home.html

Now in the home.html document, you are going to add in the following script lines inside the script tag:

<script>
      window.history.forward();
</script>

In these lines, we are accessing the history of the browser’s window object and then calling the forward() method to move the browser back to the second page. Thus messing with the habitual flow of the back button of the browser.

Key-point

This script will only work when history has some onward entry to go to. This means that the first-time loading of the webpage will never be affected by this.

After this, simply open the home webpage, click the link to go to the second webpage, and then try clicking the back button of the browser, and you will get the following output:

As you can see, clicking the back button on the browser’s doesn’t take us back to the home.html rather it takes us again on the secondPage.html

Conclusion

To stop the working of the browser’s back button with the help of JavaScript. You can simply call the forward() method on the history of the web browser merienda the webpage has loaded. Now to get access to this history, we must use the window object. This article has demonstrated the working of the window.history.forward() method to stop the working of the back button of the browser.



Source link


An HTML form can easily be submitted by clicking on any HTML element with the help of JavaScript. The form element has a submit() method, and invoking this method with an external call will submit the form.

This article is going to focus on submitting a form upon pressing a link. To showcase this, a form will be created which is going to take in the sign-up details from the user, and upon the submission of the form, it is going to simply print out the name of the user onto the console.

Step 1: Setup the HTML Elements

Create a new HTML document, and in that document, create a form with a particular ID, and within that form, create the input field for username and password. After that, instead of the submit button, create a new link by using the <a> tag and use the onclick attribute and set it equal to linkPress() function:

<center>
      <form id=«form»>
        <p>Please Type Your Username</p>
        <input id=«name» type=«text» placeholder=«Name» />
        <br />
        <p>Please type your password</p>
        <input id=«password» type=«password» placeholder=«Password» />
        <br />
        <br />
        <a href=«» onclick=«linkPress()»>Link for Submission</a>
      </form>
</center>

At this point, this HTML document produces the following webpage:

Our webpage includes two input fields and a link that has an onclick() attribute set to it.

Step 2: Making the Form “submit” on Link Press

Every form element in the HTML contains the submit() method. To submit a form, it must be referenced in the JavaScript, and then the submit() method must be called using that reference. In the script file, create the function linkPress() and add the functionality using the following lines:

function linkPress() {
  form = document.getElementById(«form»);
  form.submit();
}

First line gets the reference of our form tag and stores it inside the variable “form”. The second line uses that reference and then calls the submit() of the form. Running this HTML document gives the following result:

Pressing the link submits the form, but since there is no backend file connected to receive the form, therefore it just resets the field.

Step 3: Prompt the “username” Upon Form Submission

You want to add a function ready() upon the complete loading of the webpage; therefore, add the property of “onload” on the <body> tag like:

 <body onload=«ready()»>

And then in the script file, add the following lines:

function ready() {
  form = document.getElementById(«form»);
  form.addEventListener(«submit», function (event) {
    event.preventDefault();
    name = document.getElementById(«name»).value;
    alert(«Welcome « + name);
  });
}

When the HTML document is completely loaded:

  • An Event listener is added onto the form element by using its reference.
  • This event listener listens to the submit event
  • Upon submission, it prevents the form’s default behavior (stop the redirection).
  • At the end, it greets the user using its username.

If the webpage is loaded now, it gives the following output:

As you can see, the form was submitted, and by preventing the default behavior, we were able to avoid the need for a backend to manage the data from the fields.

Conclusion

It is really easy to submit a form by clicking a link with the help of JavaScript. The form element of an HTML document has this method called submit(). To submit the form, you only have to make an explicit call to this method, which we have done in this article.



Source link


JavaScript offers numerous methods to fulfill the requirements of programmers by executing the block of code. For scheduling a timeout, JavaScript provides methods including setInterval(), setTimeout, clearTimeout(), and clearInterval(). It provides a timeout functionality that allows users to perform any operation after a specific time interval. Moreover, the piece of code is repeated after a set interval of time. These methods are useful for sensitive websites such as banking websites and e-commerce sites.

This post demonstrates the working and usage of clearTimeout() and clearInterval() methods:

  • How to Utilize clearTimeout() Method in JavaScript
  • How to Utilize clearInterval() Method in JavaScript

JavaScript clearTimeout() and clearInterval() Methods

In JavaScript, the clearTimeout() and clearInterval() methods are used to clear the timer that was initialized using the setInterval() and setTimeout() methods, respectively. The clearTimeout() method cancels the timeout that was earlier set by the setTimeout(). The same procedure is applied using clearInterval() to antipara the time interval fixed by setInterval().

How to Utilize the clearTimeout() Method in JavaScript?

The clearInterval() method is utilized to stop the execution that started with the setTimeout() method. The method takes the same variable name that was returned by the setTimeout() method. The syntax of the clearTimeout() method is provided here:

Syntax

The timeoutID is the value of the timer set by the setTimeout() method. It is a mandatory field.

Example

An example is explained with the usage of the clearTimeout() method in JavaScript.

Code

<html>
  <body>
    <h2> An example of using the clearTimeout() method in JavaScript</h2>
    <button onclick=«startCount()»>Press Button to Start counter</button>
    <input type=«text» id=«txt»>
    <button onclick=«stopCount()»>Press Button to Stop counter</button>
    <script>
      var timer = 0;
      var time;
      var counter = 0;
      function timedCount() {
          document.getElementById(«txt»).value = counter;
          counter = counter + 1;
          time = setTimeout(timedCount, 1000);}
      function startCount() {
          if (!timer) {
            timer = 1;
            timedCount();}}
      function stopCount() {
          clearTimeout(time);
          timer = 0;}
    </script>
  </body>
</html>

In the above code, the clearTimeout() method is utilized with the setTimeout() method to differentiate the working process between them. The description is provided in the listed format:

  • Firstly, a button “Press Button to Start counter” is attached with a startCount() method.
  • Another button is associated with the stopCount() method to stop the execution of the above method.
  • After pressing the button, the counter variable is initialized and incremented by one every 1000 milliseconds.
  • These values are stored in the time variable that is utilized to stop the counter by passing it to the clearTimeout() method.

The screenshot of the above code is as follows:

Output

It is observed that the counter starts after pressing the “Press Button to Start counter” button. The counter increments the value by adding one. The process is continued until the “Press Button to Stop counter” button is pressed.

How to Utilize the clearInterval() Method in JavaScript?

This method clears the schedule created by the setInterval() method. The execution of the created timer is finished by passing the same variable that was returned from the setInterval() method. The following syntax refers to the setInterval() method.

Syntax

clearInterval(intervalID)

In this syntax, the intervalID is the passing variable that utilizes the same value as the setInterval() method.

Example
The example code written below refers to the clearTimeout() method in JavaScript.

Code

<h2> An example of using the clearInterval() method in JavaScript</h2>
<p>Press Button to start an interval that prints a message. </p>
<button id=«btn» onclick=«Result()»>Press Button to Start Interval</button>
<button id=«antipara»>Press Button to antipara interval</button>
<div id=«output»></div>
<script>
function Result() {
document.getElementById(‘antipara’).addEventListener(‘click’, () => { cancelInterval() })
const intervalID = setInterval(() => {
document.getElementById(‘output’).textContent += «Is JavaScript a Scripting Language ? «;
},500);
function cancelInterval() {
clearInterval(intervalID);
document.getElementById(‘output’).textContent = » Cancelled Interval !»;
}
}
</script>

The code is described as:

  • Two buttons are associated with the methods.
  • The Result() method is employed with a button “Press Button to Start Interval”.
  • First, the interval is set by the setInterval() method.
  • After that, a message asking, “Is JavaScript a scripting language?” is displayed every 500 milliseconds.
  • In the end, the clearInterval() method is used by passing the same variable returned by the setInterval() method.

Output

In the output, the message “Is JavaScript a scripting language?” is displayed repeatedly by pressing the Start Interval button. After that, the clearInterval() method is utilized to stop the execution and display a message “Canceled Interval”.

Conclusion

JavaScript provides functionality to stop the execution of code by utilizing the clearTimeout() and clearInterval() methods. The clearTimeout() method is employed to clear the timer value set by the setTimeout() method. On the other hand, the clearInterval() method stops the interval by passing the same value set by the setInterval() method in JavaScript. Here, you have learned to understand the clearTimeout() and clearInterval() methods in JavaScript.



Source link


In JavaScript, the Focus() method is used to set focus on any element of the HTML webpage, which means that it sets that element as the active element. The key point here is that it only focuses on the elements which “can” be focused on. In simple words, not all the elements can be focused on.

To better understand the focus() method, look at its syntax below:

In this syntax:

  • element: it is the reference of an HTML element inside JavaScript.
  • options: it is not a required parameter.

Example 1: Focusing on a Text Field Using the focus() Method

Start by creating a new HTML document, and in that document, create an input field and a button with the following lines:

 <center>
      <input type=«text» id=«TF1» placeholder=«I am a textField» />
      <button id=«btn1» onclick=«buttonClicked()»>
        Focus on the text field
      </button>
</center>

In the above lines:

  • Input tag has been given the id as “TF1
  • Button has the id as “btn1” and an onclick attribute set equal to “buttonClicked()”

Running this HTML document displays the following on the browser:

The text field and button are both displayed on the webpage. Now to add the functionality upon button press, add the following lines in the JavaScript file:

function buttonClicked() {
  tf = document.getElementById(«TF1»);
  tf.focus();
}

In the above JavaScript lines:

  • First create a function named as buttonClicked()
  • In that function, get the reference of the text field by using its Id and store that reference in the “tf” variable
  • After that, simply call the focus() method with the “tf” variable with the help of the dot operator

At this point, webpage produces the following outcome:

It is observable in the output, that pressing the putting puts the text field as active or “in focus”.

Example 2: Focusing on an Element With “options” Arguments

In this example, the main goal is to have an element at a scrollable position. After that, the button should not only focus on that element but also bring that element into view from the document.

Start by creating an HTML document, and just like in the first example, create a text field and a button with the following lines:

<center>
      <input
        type=«text»
        id=«TF1»
        class=«scrolled»
        placeholder=«I am a textField»
      />
      <button id=«btn1» onclick=«buttonClicked()»>
        Focus on the text field
      </button>
    </center>

In these lines the only difference is:

  • The input that now has a class “scrolled”, which will be used to place this input tag at a scrollable position in the document

After that, add the following lines to the CSS file or in the <style> tag:

body {
  height: 7000px;
}
.scrolled {
  position: absolute;
  top: 4000px;
}

In the lines mentioned above:

  • The <body> of the document has been a height of 7000px so that the document becomes scrollable
  • After that, we are setting the element with the scrolled class to an absolute position of 4000px from the top

Running this HTML document give the following webpage on the browser:

From the output, it is clear that the text field is now placed at a position of 4000px from the top.

After that, we are going to add the following lines of JavaScript:

function buttonClicked() {
  tf = document.getElementById(«TF1»);
  tf.focus({ preventScroll: false });
}

In these lines:

  • A function buttonClicked() is made
  • In that function, a reference to the text field is made by using its ID and stored inside the variable “tf”.
  • After that, apply the focus() method on the text field and in its argument pass {preventScroll:false}. This will bring the element in focus and scroll the document to bring that element in view.

Run the HTML document, and you will get the following result upon clicking the button:

It is observable from the output that upon clicking the button, the text field is brought into the view of the browser by scrolling the document. Moreover, the text field is now being focused on.

Conclusion

This article throws light on the purpose and the working of the focus() method in JavaScript. This method is used to bring an element of the HTML document into focus, or in much simpler words, it sets their active property as true. To apply this method, simply use it with the reference of the HTML element with a dot operator. This focus method can also take in an optional argument which has been demonstrated above.



Source link


The window scrollTo method is used to scroll the browser window to a specific coordinate. This method is named the scrollTo() while the window is the Window Object. A browser window that is open is represented by the window object. To better understand this method, quickly go over the syntax given below:

Syntax of the scrollTo() Method

window.scrollTo(X-coordinate, Y-coordinate);

In this syntax:

  • window is the browser’s window Object.
  • X-coordinate is the horizontal displacement to the browser’s window at.
  • Y-coordinate is the derecho displacement to pan the browser’s window at.

Demonstration of the Window scrollTo() Method

To demonstrate the working of the scrollTo method, start by creating an HTML file with the following lines:

<center>
      <b class=«scrolled»>I am Placed at 4000px Vertically</b>
      <button onclick=«clicked()»>Click me to scroll down</button>
</center>

In this above HTML code snippet,

  • A bold tag was created with some text inside it with the class being scrolled. This class will be used to place this tag at 4000px with the help of CSS.
  • A button was created which calls the clicked() function in the JavaScript file.

After that is done, we want to add the following lines to the CSS of our webpage:

body {
  height: 7000px;
}
.scrolled {
  position: absolute;
  top: 4000px;
}

In the above CSS snippet:

  • The height of the body tag is set to 7000px so the webpage becomes scrollable even without having more elements on it.
  • The bold tag with the class scrolled has been placed at 4000px.

Executing the webpage now provides us the following output on the browser’s window:

As you can see from the output, to visit the bold tag, one must manually scroll the browser’s window.

To add functionality to the button so that it scrolls us directly on the bold tag with text, write the following lines in the script file:

function clicked() {
  window.scrollTo(0, 4000);
}

In these lines, the function clicked() is created, which is called upon pressing the button, and in this function, we are simply passing the Y-coordinate as 4000px to the window scrollTo() method. This provides the following outcome on the HTML webpage:

As it is clearly shown in the output, pressing the button pans the browser’s window to 4000px vertically.

Wrap up

The window scrollTo() method is used to call the browser’s window object and then pan the browser’s window to a specific position by passing in the x and y coordinates in its arguments. This article demonstrated the working of the window scrollTo() method with the help of an example.



Source link


In JavaScript, the onclick event of the button is used to associate any JavaScript function with it. Whenever the user presses the button, the attached function will be triggered. JavaScript provides built-in features such as addevent listener and onclick events to execute multiple functions with a single click. This event supports all the famous web browsers. In this article, you will learn how to call multiple JavaScript functions with an onclick event.

How to Call Multiple JavaScript Functions With an onclick Event?

The onclick event executes multiple methods in sequential order with a single click and supports multiple browsers. The onclick event makes the script clear and understandable by separating the functions with a semicolon for the users. The following example refers to the practical implementation of the onclick event.

Example

An example is provided of calling multiple functions by using the onclick event in JavaScript. For this purpose, the code is written as below:

Code

<html>
<head>
<h2>An example of using multiple methods by onclick event </h2>
<script>
// An example of using multiple methods by onclick event
document.write(«<br>»);
function method1() {
document.write («First Method is called»);
document.write(«<br>»);
document.write («Welcome to JavaScript World»);
document.write(«<br>»);
document.write(«<br>»);
}
function method2() {
document.write («Second Method is called»);
document.write(«<br>»);
document.write (» Welcome to Linuxhint»);
}
</script>
</head>
<body>
<p>Press magic button to call the multiple functions</p>
<form>
<input type=«button» onclick = «method1(); method2()» value = «Press the Magic Button» >
</form>
</body>
</html>

 
The description of the code is as follows:

    • Two functions named method1() and method2() are defined that are to be called after the onclick event.
    • After that, a button is created using the <form> tag.
    • On the onclick event of the button, the methods method1() and method2() will be triggered.

Output

A button named “Press the Magic Button” is utilized to execute the multiple methods by its onclick event. After pressing the button, method1 and method2 are called to display the information present in it.


After pressing the button, two methods are called and display messages “Welcome to JavaScript World” and “Welcome to Linuxhint”.

Conclusion

In JavaScript, an onclick event is employed to call multiple functions with a single click. These functions are placed in the onclick event of the button type. This post demonstrates the usage of the onclick event to call multiple functions in JavaScript. For a better understanding, we have demonstrated an example that shows how multiple functions are called with a single click.



Source link