Web Design JavaScript

https://javascript.info/

https://www.w3schools.com/js/

https://www.freecodecamp.org/learn/full-stack-developer/


animated text:: https://animate.style/

slider:: https://swiperjs.com/

https://www.youtube.com/watch?v=9ERwhR-3mN0&list=PL2NDx92_iOAG8QMxe_0WfdHOcekx7aX-M&index=11


Slider:: https://kenwheeler.github.io/slick/



Part A: Basic JavaScript Concepts

  1. What is JavaScript used for in web design?

JavaScript is used to create dynamic and interactive elements on websites, such as drop-down menus, modals, image sliders, and real-time content updates without reloading the page.

2.      Application of JavaScript in Web Design

a)      JavaScript used to enhance user interactivity on a website

b)      JavaScript contribute to form validation

c)      JavaScript play in dynamic content loading

d)      JavaScript be used to improve navigation in web design

e)      JavaScript important for responsive web design

  1. Is JavaScript a client-side or server-side language?

JavaScript is mainly a client-side scripting language but can also be used server-side with environments like Node.js.

  1. List of JavaScript Framework.
    • React
    • Vue.js
    • Angular js
    • Ember js
  2. How do you declare a variable in JavaScript?

Variables can be declared using var, let, or const. Example: let x = 5; let is block-scoped, var is function-scoped, and const is block-scoped and constant.

  1. How many ways to display output in JS
    1. Writing into an HTML element, using innerHTML or innerText.
    2. Writing into the HTML output using document.write().
    3. Writing into an alert box, using window.alert().
    4. Writing into the browser console, using console.log().

<body>

    <p id="demo">Hello</p>

    <script>

        document.write("Hello World");

        console.log("Hello Console");

        window.alert("Hello Window");

        document.getElementById("demo").innerText="Nothing";

    </script>

</body>

 

 ** difference between innerHTML or innerText

·         Use innerHTML when you need to manipulate or retrieve the full HTML structure and content of an element, including tags.

·         Use innerText when you primarily need to work with the visible, plain text content of an element and want to avoid potential security risks associated with HTML parsing.

7.      What are the different types of operators in JavaScript?

JavaScript supports arithmetic, assignment, comparison, logical, bitwise, and ternary operators.

Feature

var

let

const

Scope

Function

Block

Block

Hoisting

Yes (initialized to undefined)

Yes (TDZ*)

Yes (TDZ*)

Re-declaration

Allowed

Not in same scope

Not in same scope

Re-assignment

Allowed

Allowed

Not allowed

 

8.      What does the logical AND (&&) operator do in JavaScript?

It returns true if both operands are true; otherwise, it returns false. It is commonly used in conditional statements.

 

  1. What is the difference between == and === in JavaScript?

== compares values, while === checks for both value and type equality, making it stricter.

10.  What is the purpose of the modulus (%) operator?

The modulus operator returns the remainder after division of one number by another. Example: 7 % 3 equals 1.

11.  What is the use of the increment (++) operator?

It increases a variable’s value by 1. It can be used as either a prefix (++x) or postfix (x++).

12.  What is a ternary operator in JavaScript?

It is a shorthand for if-else conditions. Syntax: condition ? valueIfTrue : valueIfFalse

  1. How can you include JavaScript code in an HTML file?
    • JavaScript in Head

<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</head>

    • JavaScript in Body

<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>

    • External JavaScript: myScript.js

                   <script src="myScript.js"></script>

 

 

  1. Why use comment in JavaScript?

JavaScript comments can be used to explain JavaScript code, and to make it more readable.

o    Single line comment:  // Change heading

o    Multi-line comments:

/*
The code below will change
in my web page:
*/

  1. What is the output of: console.log(typeof "Hello")?

The output is "string" because "Hello" is a text value.

  1. What will be the output of: console.log(2 + "3")?

The result is "23" because the number is converted to a string and concatenated.

  1. What data types are supported in JavaScript?

JavaScript supports String, Number, Boolean, Undefined, Null, Object, Symbol, and BigInt.

18.  What is an alert box in JavaScript?

An alert box is a simple popup message that displays information to the user and requires them to click OK to proceed. It is created using alert("message");

19.  What is a confirm box in JavaScript

A confirm box asks the user to confirm or cancel an action. It returns true if the user clicks OK, and false if Cancel is clicked. Example: confirm("Are you sure?");

20.  What is a prompt box in JavaScript?

A prompt box asks the user for input. It displays a message and a text input field, and returns the input or null if the user cancels. Example: prompt("Enter your name:");

21.  How can you use the return value of a confirm or prompt box?

You can assign the result to a variable and use it in conditions. Example: let result = confirm("Delete?"); if(result) { // proceed }

 

 

Control Statement

Arrays

Object

 

Function

2.       What is a function in JavaScript?
A function is a block of reusable code that performs a specific task.

3.      How do you define a function in JavaScript?

function greet() {

  console.log("Hello!");

}

4.      How do you call a function?

By writing its name followed by parentheses: greet();

5.      What is a parameter in a function?

A parameter is a variable listed in the function definition.
Example: function greet(name) { ... }

6.      What is an argument in a function?

An argument is the actual value passed to a function.
Example: greet("Imran");

7.      What is a return statement?

It returns a value from the function to the caller.

function add(a, b) {

  return a + b;

}

8.      What is an anonymous function?

An anonymous function is a function without a name. It is often used when a function is only needed once or passed as a value.

const greet = function() {

  console.log("Hello from anonymous function!");

};

greet();

Used in situations like event handlers or callbacks where naming the function isn't necessary.

9.      What is an arrow function?

An arrow function is a shorter syntax for writing function expressions.

const greet = () => {

  console.log("Hello from arrow function!");

};

10.  What is a callback function?

A callback function is a function that is passed as an argument to another function and is called inside that function after some operation is completed.

function processUserInput(callback) {

  let name = "Imran";

  callback(name);

}

 

processUserInput(function(name) {

  console.log("Hello " + name);

});

11.  Can a function be stored in a variable?

Yes

12.  Difference between Function and Method in JavaScript

Function: A function is a standalone block of code designed to perform a specific task. It can be defined and invoked independently, without being tied to any particular object. Functions can take arguments and return values

    function greet(name) {

        console.log("Hello, " + name + "!");

    }

    greet("Alice"); // Invoking a standalone function

Method: A method is a function that is associated with an object. It is a property of an object and is designed to operate on the data or properties of that specific object. Methods are invoked using dot notation on an object instance

    const person = {

        name: "Bob",

        age: 30,

        introduce: function() { // This is a method

            console.log("Hi, my name is " + this.name + " and I am " + this.age + " years old.");

        }

    };

    person.introduce(); // Invoking a method on the 'person' object

 


 

Part B: Working with the DOM

  1. What is the DOM in JavaScript?

The Document Object Model is a tree-like structure representing HTML elements as objects that can be accessed and modified using JavaScript.

HTML DOM

src:tutorialspoint.com

  1. How do you access an element by its ID?

By using document.getElementById("elementId").

  1. How do you change the text content of an HTML element?

You can use innerText or textContent to update an element's visible text.

  1. How do you change the HTML content of an element?

Use innerHTML to inject or replace HTML content. Example: element.innerHTML = "New Content";

  1. How can you change the style of an HTML element?

Modify the style property, e.g., element.style.color = "blue";

  1. How do you add a new element to the DOM?

Use document.createElement to create and appendChild to insert it into the DOM tree.

  1. How can you remove an element from the DOM?

Use parentElement.removeChild(childElement) to delete an element.

  1. What does querySelector do?

It selects and returns the first DOM element that matches a specified CSS selector.

  1. What does querySelectorAll return?

It returns a static NodeList of all elements matching the given CSS selector.

  1. How can you get or set the value of an input field?

Use inputElement.value to retrieve or assign the value of the field.

Part C: Events and Interactivity

21. What is an event in JavaScript?

An event in JavaScript is an action or occurrence that happens in the browser, which the JavaScript code can respond to. Common examples include user interactions like clicking a button, typing in a field, moving the mouse, or loading a page. JavaScript uses events to create interactive web pages.

22. How do you handle an event in JavaScript?

Events are handled by attaching event listeners to HTML elements. This is commonly done using the addEventListener method. When the specified event occurs on the element, the provided function (event handler) is executed.

Example:

const button = document.querySelector("button");

button.addEventListener("click", function() {

  alert("Button clicked!");

});

23. How do you stop a form from submitting?

To stop a form from submitting (i.e., prevent it from sending data and reloading the page), use the event.preventDefault() method inside the form's submit event handler.

Example:

const form = document.querySelector("form");

form.addEventListener("submit", function(event) {

  event.preventDefault(); // Stops form from submitting

  alert("Form submission prevented!");

});

 

24.What does event.target refer to?

event.target is a property of the event object that refers to the actual HTML element that triggered the event. This is useful when a single event listener is used for multiple elements, and you want to know exactly which element was interacted with.

Example:

document.addEventListener("click", function(event) {

  console.log("You clicked on:", event.target.tagName);

});

 

25. How can you run a function when the page loads?

To run a function when the page has finished loading, you can use either:

  • window.onload = function() { ... }, or
  • window.addEventListener("load", function() { ... })

Example:

window.addEventListener("load", function() {

  console.log("The page is fully loaded.");

});

26. How do you add a mouseover event?

You can use addEventListener("mouseover", ...) to run a function when the mouse pointer moves over an element.

Example:

const box = document.getElementById("hoverBox");

box.addEventListener("mouseover", function() {

  box.style.backgroundColor = "lightblue";

});

27. What does the onchange event do?

The onchange event is triggered when the value of an input, select, or textarea element is changed and the element loses focus. It's commonly used in forms to detect user input changes.

Example:

const select = document.getElementById("fruits");

select.addEventListener("change", function() {

  console.log("Selected:", this.value);

});

28. What is the purpose of event bubbling?

Event bubbling is a process in which an event triggered on a nested element propagates upward through its ancestors in the DOM. This allows parent elements to respond to events from child elements, making event management easier and more flexible.

For example, clicking a <span> inside a <div> can trigger click events on both the <span> and the <div> due to bubbling.

29. How can you prevent event bubbling?

To stop an event from bubbling up to parent elements, you use event.stopPropagation() in the event handler.

Example:

document.getElementById("child").addEventListener("click", function(event) {

  event.stopPropagation(); // Prevents bubbling to parent

  alert("Child clicked!");

});

30. What does event delegation mean?

Event delegation is a powerful JavaScript pattern where a single event listener is attached to a parent element to handle events from its child elements. Instead of assigning event listeners to each child individually, you allow the event to bubble up to the parent and then identify the target using event.target.

This approach improves performance and is especially helpful when dealing with dynamic elements that are added after the page loads.

<ul id="myList">

  <li>Item 1</li>

  <li>Item 2</li>

  <li>Item 3</li>

</ul>

******JavaScript

// Attach one click listener to the parent <ul>

document.getElementById("myList").addEventListener("click", function(event) {

  // Check if a <li> was clicked

  if (event.target.tagName === "LI") {

    alert("You clicked: " + event.target.textContent);

  }

});

Even if you add a new item dynamically like this:

const newItem = document.createElement("li");

newItem.textContent = "Item 4";

document.getElementById("myList").appendChild(newItem);

 

 

 

Part D: JavaScript in Web Design

  1. How does JavaScript enhance user experience on a website?

It enables real-time updates, animation, validation, and feedback without reloading the page, making interactions smooth and engaging.

  1. Give an example of using JavaScript for form validation.

Example: if (document.getElementById("email").value === "") { alert("Email is required"); } — this checks if the email field is empty.

  1. How can JavaScript change the CSS class of an element?

By assigning a new value to the element's className property: element.className = "new-class";

34. How can JavaScript toggle a class on an element?

You can use the classList.toggle() method to add a class if it's not present or remove it if it is. This is useful for changing styles dynamically (like activating a menu or changing themes).

Example:

<button id="toggleBtn">Toggle Highlight</button>

<p id="text">This is a paragraph.</p>

 

<style>

  .highlight {

    background-color: yellow;

  }

</style>

 

<script>

  const btn = document.getElementById("toggleBtn");

  const text = document.getElementById("text");

 

  btn.addEventListener("click", function() {

    text.classList.toggle("highlight");

  });

</script>

35. How can you hide an element using JavaScript?

To hide an element, you can change its CSS display property using JavaScript. Setting display = "none" removes it from the page layout.

Example:

<button onclick="hideElement()">Hide</button>

<p id="para">This paragraph will disappear when you click the button.</p>

<script>

  function hideElement() {

    document.getElementById("para").style.display = "none";

  }

</script>

36. How can you make an image slider using JavaScript?

You can create an image slider by:

  1. Storing image URLs in an array.
  2. Changing the src of an <img> tag periodically using setInterval() or based on user clicks.

 

37. How do you create a dropdown menu using JavaScript?

To create a dropdown menu, you can:

  • Initially hide the menu using CSS.
  • Use JavaScript to toggle its visibility when a button is clicked.

Example

<button onclick="toggleMenu()">Toggle Menu</button>

<ul id="dropdown" style="display: none;">

  <li>Option 1</li>

  <li>Option 2</li>

  <li>Option 3</li>

</ul>

 

<script>

  function toggleMenu() {

    const menu = document.getElementById("dropdown");

    if (menu.style.display === "none") {

      menu.style.display = "block";

    } else {

      menu.style.display = "none";

    }

  }

</script>

 

38. How can you dynamically change text content on a webpage?

You can change text using .innerText or .textContent on an element. This is useful when updating content based on user actions or API results.

Example:

<p id="message">Hello!</p>

<button onclick="changeText()">Change Text</button>

 

<script>

  function changeText() {

    document.getElementById("message").innerText = "Text has been changed!";

  }

</script>

39. What is AJAX and how does it relate to JavaScript?

AJAX (Asynchronous JavaScript and XML) is a technique that allows web pages to request data from a server and update parts of the page without reloading. It improves user experience by making web apps faster and more dynamic.

40. What does the fetch API do?

The fetch() API is a modern way to make network requests. It returns a Promise, which you can handle using .then() and .catch() to process responses asynchronously.

Example:

fetch("https://jsonplaceholder.typicode.com/posts/1")

  .then(response => response.json())

  .then(data => {

    console.log("Post Title:", data.title);

  })

  .catch(error => {

    console.error("Error fetching data:", error);

  });

 

Part E: Programming Logic and Advanced Topics

  1. What is a loop in JavaScript?

A control structure that repeats a block of code while a condition is true.

  1. Name the different types of loops in JavaScript.

for, while, do...while, for...in, for...of, and forEach (for arrays).

  1. What is an array in JavaScript?

A data structure that holds a collection of values, accessible by index.

  1. How do you declare an object in JavaScript?

Use curly braces: let person = { name: "John", age: 30 };

  1. How do you access a property of an object?

Using dot notation (obj.key) or bracket notation (obj["key"]).

  1. What is JSON in JavaScript?

JavaScript Object Notation, a lightweight format for storing and exchanging data.

  1. How do you parse a JSON string into a JavaScript object?

Use JSON.parse(jsonString) to convert JSON text into a usable object.

 

 

//////////////////////////

1. What is the purpose of <noscript> tag?

The <noscript> tag is used to provide alternate content for users who:

  • Have JavaScript disabled in their browser.
  • Are using a browser that doesn't support JavaScript.

<noscript>

  <p>Your browser does not support JavaScript or it is disabled.</p>

</noscript>

2. How can you disable browser from validation?

You can disable HTML5 form validation by using the novalidate attribute in the <form> tag.

<form novalidate>

  <input type="email" required>

  <button type="submit">Submit</button>

</form>

3. What is the Geolocation API?

The Geolocation API allows web applications to access the geographical location (latitude, longitude, altitude, etc.) of the user, with their consent.

navigator.geolocation.getCurrentPosition(function(position) {

  console.log(position.coords.latitude, position.coords.longitude);

});

4. What is Web Storage API (localStorage/sessionStorage)?

The Web Storage API allows you to store data in a user's browser. It has two types:

  • localStorage: Stores data with no expiration time.
  • sessionStorage: Stores data only for the duration of the session (until the tab is closed).

// localStorage

localStorage.setItem("name", "Imran");

// sessionStorage

sessionStorage.setItem("token", "abc123");

5.What is CMS

A Content Management System (CMS) is software that allows users to create, manage, and modify digital content, typically for websites, without needing specialized technical knowledge. Eg. Wordpress, Joomla, Webflow,

6. How CMS integrates multiple users?

A CMS (Content Management System) integrates multiple users by:

  • Providing user roles (Admin, Editor, Contributor, Viewer).
  • Managing permissions (who can create, edit, publish, or delete content).
  • Offering login/authentication systems.

Example: WordPress allows admins to manage users and assign different capabilities.

7. How jQuery simplifies DOM manipulation?

jQuery simplifies DOM manipulation by:

  • Using concise syntax to select and modify HTML elements.
  • Handling cross-browser inconsistencies.
  • Providing built-in methods for events, animations, and AJAX.

// Pure JavaScript

document.getElementById("title").style.color = "red";

// jQuery

$("#title").css("color", "red");

8. What are three common features of a CMS?

 Ans: The three common features of a CMS are:

1. Content Creation and Editing: Easy-to-use editors for creating and formatting content, along with options for structured content and media management.

2. User Management and Permissions: The ability to assign different roles to users with specific permissions to control who can access and edit content.

3. Content Publishing and Workflow Management: Features like drafts, content scheduling, and approval workflows to manage the creation and publication process efficiently.

9. How does FTP client  Works?

. User connects to an FTP server with authentication credentials.

2. FTP client sends commands to the server (e.g., to list files, navigate directories).

 3. Data connection is established for transferring files.

4. File transfer occurs via the data connection, using either binary or ASCII mode.

5. User disconnects after completing the tasks, closing the connection.

10. What is the significance of adhering to web standards in achieving cross-browser compatibility?

Adhering to web standards:

  • Ensures your site behaves consistently across different browsers.
  • Reduces rendering bugs and maintenance.
  • Improves accessibility and performance.

 

11. What is DBMS?

DBMS (Database Management System) is software that allows users to create, manage, and interact with databases.

Features:

  • Data storage, retrieval, and manipulation.
  • Security and access control.
  • Examples: MySQL, PostgreSQL, Oracle, SQL Server.

12.What role does a database play in a CMS?

 Ans: The database in a CMS is essential for content storage, dynamic content management, user data management, and site configuration. It ensures the CMS operates efficiently by storing and organizing data, facilitating content creation and editing, and ensuring that users have the correct permissions. The database is the backbone that makes the CMS flexible, powerful, and able to scale with content and users.

 

13.What are the three main components involved in Client-Server setup?

 1. Client: It can be a computer, mobile device, or software application that interacts with the server to access data or functionality.

2. Server: The server is a powerful computer or program that provides services, resources, or data to the client.

 3. Network: The network facilitates communication between the client and server.

 

14. What is AJAX in jQuery?

 Ans: AJAX (Asynchronous JavaScript and XML) in jQuery refers to a technique that allows web pages to fetch data from a server asynchronously, without reloading the entire page. This helps to create dynamic, faster, and more interactive web applications.

 15. How does jQuery simplify DOM manipulation?

 Ans: jQuery simplifies DOM manipulation by providing an intuitive, consistent, and cross-browser-compatible API. It reduces the amount of code developers need to write for common tasks, such as selecting elements, changing their content, handling events, applying styles, and creating animations. This makes web development faster and more efficient, especially when building dynamic, interactive web applications.

16. How does a CMS enable collaboration among multiple users?

Ans: A Content Management System (CMS) enables collaboration among multiple users by providing a centralized platform where users can create, edit, manage, and publish content together. The collaborative features of a CMS allow different users to work on the same website or application, each with specific roles, permissions, and workflows to ensure smooth and organized teamwork.

17.What is JSON?

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight data-interchange format
  • JSON is plain text written in JavaScript object notation
  • JSON is used to send data between computers

 

 


Comments

Popular posts from this blog

Basic Web Design with HTML and CSS

Project Web Design Assignment