Join Regular Classroom : Visit ClassroomTech

JavaScript – codewindow.in

Related Topics

HTML

Introduction
Html page 1
Html page 2
Html page3
Html page4

HTML Elements and structure
Html page 5
Html page 6
Html page 7

HTML Headings and Paragraphs
Html page 8
Html page 9
Html page 10

HTML Lists and Tables
Html page 11
Html page 12
Html page 13

HTML Forms and Input Fields
Html page 14
Html page 15
Html page 16

HTML Images and Media
Html page 17
Html page 18

HTML Links and Anchors
Html page 19
Html page 20
Html page 21

HTML Styles and Formatting
Html page 22

HTML Semantic Elements
Html page 23
Html page 24

HTML Attributes
Html page 25
Html page 26

HTML JavaScript Integration
Html page 27
Html page 28
Html page 29
Html page 30

HTML Document and Browser Support
Html page 31
Html page 32

HTML5 New Elements and Attributes
Html page 33
Html page 34
Html page 35
Html page 36

HTML Accessibility and Web Standards
Html page 37
Html page 38
Html page 39

HTML Responsive Design and Mobile Devices.
Html page 40
Html page 41
Html page 42

JAVASCRIPT




    <title>Form Validation Example</title>


    
        <label for="name">Name:</label>
        
        <br>
        <label for="email">Email:</label>
        
        <br>
        
    

    
        const form = document.getElementById('myForm');

        form.addEventListener('submit', function (event) {
            // Prevent the default form submission
            event.preventDefault();

            // Perform form validation here
            validateForm();
        });

        function validateForm() {
            // Get form elements by their IDs
            const nameInput = document.getElementById('name');
            const emailInput = document.getElementById('email');

            // Get the input values
            const nameValue = nameInput.value.trim();
            const emailValue = emailInput.value.trim();

            // Validate name field (Example: Must be at least 3 characters long)
            if (nameValue.length &lt; 3) {
                alert(&#039;Name must be at least 3 characters long.&#039;);
                return false;
            }

            // Validate email field (Example: Must be a valid email format)
            const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailPattern.test(emailValue)) {
                alert(&#039;Please enter a valid email address.&#039;);
                return false;
            }

            // If all validations pass, you can submit the form
            alert(&#039;Form submitted successfully!&#039;);
            form.submit();
        }
    


In the example above, we use the addEventListener method to attach a submit event handler to the form. When the form is submitted, the event handler function (validateForm) is called.
Inside the validateForm function:
  1. We retrieve the input values from the name and email fields using the value property of their corresponding DOM elements.
  2. We then perform validation checks on these values. For the name field, we check if it’s at least 3 characters long. For the email field, we use a regular expression pattern to check if it matches a valid email format.
  3. If any validation fails, an alert is shown to the user with an error message, and the form submission is prevented using event.preventDefault().
  4. If all validations pass, an alert is shown indicating that the form was submitted successfully, and we proceed to submit the form using form.submit().
Remember that client-side form validation is essential for improving user experience and reducing unnecessary server requests. However, it should always be complemented by server-side validation to ensure the submitted data is validated and sanitized on the server as well. Client-side validation can be bypassed, so it’s not a substitute for proper server-side validation.
document.getElementById('button').addEventListener('click', function(event) {
  event.stopPropagation(); // Stop event from bubbling up to outer
  event.preventDefault(); // Prevent the default behavior of the click event
  // Your event handling code here
});
Understanding event bubbling and capturing is essential for managing event handling efficiently, especially when multiple event listeners are attached to different elements within the DOM hierarchy. It allows you to handle events at various levels in the hierarchy and provides flexibility in managing event flow and interactions in your web application.
const xhr = new XMLHttpRequest();
2. Configure the Request: Set up the request using the open() method. The open() method takes three arguments: the HTTP method (e.g., ‘GET’, ‘POST’), the URL to which the request is sent, and whether the request should be asynchronous (usually set to true).
xhr.open('GET', 'https://api.example.com/data', true);
  1. Set Up Event Listeners: To handle the server’s response, set up event listeners for the XMLHttpRequest object. You’ll typically listen for the readystatechange event, which is triggered whenever the readyState property of the XMLHttpRequest object changes. Additionally, you can listen for the load event, which is triggered when the request is successfully completed.
xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      // Request was successful, and the response is available in xhr.responseText
      console.log(xhr.responseText);
    } else {
      // Handle the error
      console.error('Error occurred:', xhr.status, xhr.statusText);
    }
  }
};

xhr.addEventListener('load', function() {
  console.log('Request completed successfully!');
});
4. Send the Request: Finally, send the request using the send() method. If you’re making a POST request and need to send data to the server, pass the data as an argument to the send() method.
xhr.send();
Putting it all together, here’s a complete example of making an AJAX GET request:
const xhr = new XMLHttpRequest();

xhr.open('GET', 'https://api.example.com/data', true);

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      console.log(xhr.responseText);
    } else {
      console.error('Error occurred:', xhr.status, xhr.statusText);
    }
  }
};

xhr.addEventListener('load', function() {
  console.log('Request completed successfully!');
});

xhr.send();
Keep in mind that modern web development often utilizes Fetch API or other libraries like Axios or jQuery for handling AJAX requests, as they provide more streamlined and user-friendly APIs for making asynchronous HTTP requests. However, XMLHttpRequest is still a fundamental technique and can be used when compatibility with older browsers is a concern or when working on legacy projects.
<div id="myDiv">
    <p>This is <strong>bold</strong> text.</p>
</div>
const myDiv = document.getElementById('myDiv');

// Reading innerHTML
console.log(myDiv.innerHTML); // Output: "<p>This is <strong>bold</strong> text.</p>"

// Setting innerHTML
myDiv.innerHTML = "<p>New paragraph.</p>";
  1. textContent: The textContent property, on the other hand, allows you to access or modify only the text content within an element, excluding any HTML tags. When you read the textContent property, it returns the text content as a plain string, without any HTML tags. When you set the textContent property, it replaces the existing text content with the new text.
Example:
<div id="myDiv">
    <p>This is <strong>bold</strong> text.</p>
</div>
const myDiv = document.getElementById('myDiv');

// Reading textContent
console.log(myDiv.textContent); // Output: "This is bold text."

// Setting textContent
myDiv.textContent = "New paragraph.";
In summary:
  • innerHTML is used to manipulate the HTML content, including HTML tags and text.
  • textContent is used to manipulate only the plain text content without any HTML tags.
When updating content, you should be careful with innerHTML as it can introduce security risks like cross-site scripting (XSS) attacks if the content is not properly sanitized. Whenever possible, use textContent to update text content, and use other DOM manipulation methods to create and append elements to ensure security and consistency.



    <title>Drag and Drop Example</title>
    
        #draggableElement {
            width: 100px;
            height: 100px;
            background-color: blue;
            color: white;
            text-align: center;
            line-height: 100px;
            position: absolute;
            cursor: move;
        }
    


    <div id="draggableElement">Drag Me!</div>

    
        const draggableElement = document.getElementById('draggableElement');
        let offsetX, offsetY, isDragging = false;

        draggableElement.addEventListener('mousedown', (event) =&gt; {
            // Calculate the offset between the click point and the top-left corner of the element
            offsetX = event.clientX - draggableElement.offsetLeft;
            offsetY = event.clientY - draggableElement.offsetTop;
            isDragging = true;
        });

        document.addEventListener('mousemove', (event) =&gt; {
            if (isDragging) {
                // Move the element to the new position
                draggableElement.style.left = (event.clientX - offsetX) + 'px';
                draggableElement.style.top = (event.clientY - offsetY) + 'px';
            }
        });

        document.addEventListener('mouseup', () =&gt; {
            isDragging = false;
        });
    


In this example, we create a blue box with the text “Drag Me!” inside it. The box can be dragged by clicking on it and moving the mouse. Here’s a breakdown of how it works:
  1. We select the draggable element using document.getElementById.
  2. When the mousedown event occurs on the element, we calculate the offset between the mouse click point and the top-left corner of the element (offsetX and offsetY).
  3. While the mouse is moving (mousemove event), if the isDragging flag is set to true (indicating that the mouse button is being held down), we adjust the element’s position (left and top CSS properties) based on the mouse position and the calculated offsets.
  4. When the mouseup event occurs, we set isDragging to false to indicate that dragging has stopped.
The position: absolute CSS property is used to enable precise positioning of the draggable element based on its left and top values.
This example demonstrates a simple implementation of drag and drop functionality. For more complex scenarios or to handle multiple draggable elements, you may need to consider additional features like z-index handling, constraining movement within a specific area, or handling overlaps between draggable elements. Libraries like interact.js and Draggable from GreenSock Animation Platform (GSAP) offer more advanced drag and drop features and can be helpful for complex drag and drop interactions.



    <title>Dynamic Media Loading</title>


    <button>Load Image</button>
    <div id="imageContainer"></div>

    
        function loadImage() {
            const imageUrl = 'path/to/image.jpg';
            const imageElement = new Image();
            imageElement.src = imageUrl;
            
            const imageContainer = document.getElementById('imageContainer');
            imageContainer.appendChild(imageElement);
        }
    


Example: Loading a video dynamically:



    <title>Dynamic Media Loading</title>


    <button>Load Video</button>
    <div id="videoContainer"></div>

    
        function loadVideo() {
            const videoUrl = 'path/to/video.mp4';
            const videoElement = document.createElement('video');
            videoElement.src = videoUrl;
            videoElement.controls = true; // Show video controls
            
            const videoContainer = document.getElementById('videoContainer');
            videoContainer.appendChild(videoElement);
        }
    


Modifying Attributes:
You can modify the attributes of media elements using JavaScript to change their behavior or appearance. For example, setting the src attribute of an image or video changes the media source, and the controls attribute enables or disables video controls.
Event Handling:
You can attach event listeners to media elements to respond to various events, such as playing, pausing, seeking, and error events.
Example: Attaching an event listener to a video element:
const videoElement = document.getElementById('myVideo');

videoElement.addEventListener('play', function() {
    console.log('Video started playing.');
});

videoElement.addEventListener('pause', function() {
    console.log('Video paused.');
});
Controlling Playback:
You can use JavaScript to control the playback of videos, such as starting, pausing, seeking, changing volume, and muting.
Example: Controlling video playback:
const videoElement = document.getElementById('myVideo');

function playVideo() {
    videoElement.play();
}

function pauseVideo() {
    videoElement.pause();
}

function seekTo(time) {
    videoElement.currentTime = time;
}

function setVolume(volume) {
    videoElement.volume = volume;
}

function muteVideo() {
    videoElement.muted = true;
}

function unmuteVideo() {
    videoElement.muted = false;
}
These are some common tasks you can perform with images and videos in the DOM using JavaScript. You can use these techniques to create dynamic and interactive media experiences on your web pages.

      

Popular Category

Topics for You

HTML

Introduction
Html page 1
Html page 2
Html page3
Html page4

HTML Elements and structure
Html page 5
Html page 6
Html page 7

HTML Headings and Paragraphs
Html page 8
Html page 9
Html page 10

HTML Lists and Tables
Html page 11
Html page 12
Html page 13

HTML Forms and Input Fields
Html page 14
Html page 15
Html page 16

HTML Images and Media
Html page 17
Html page 18

HTML Links and Anchors
Html page 19
Html page 20
Html page 21

HTML Styles and Formatting
Html page 22

HTML Semantic Elements
Html page 23
Html page 24

HTML Attributes
Html page 25
Html page 26

HTML JavaScript Integration
Html page 27
Html page 28
Html page 29
Html page 30

HTML Document and Browser Support
Html page 31
Html page 32

HTML5 New Elements and Attributes
Html page 33
Html page 34
Html page 35
Html page 36

HTML Accessibility and Web Standards
Html page 37
Html page 38
Html page 39

HTML Responsive Design and Mobile Devices.
Html page 40
Html page 41
Html page 42

Go through our study material. Your Job is awaiting.

Recent Posts
Categories