0% found this document useful (0 votes)
23 views4 pages

jQuery and Async JavaScript Exercises

The document discusses practice exercises on jQuery and asynchronous JavaScript. It includes 6 questions - the first 4 involve selecting and manipulating DOM elements using jQuery, the 5th adds interactivity to a responsive website footer with jQuery, and the 6th involves promises. Instructions are provided on organizing files.

Uploaded by

Haregewoyn Deyu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views4 pages

jQuery and Async JavaScript Exercises

The document discusses practice exercises on jQuery and asynchronous JavaScript. It includes 6 questions - the first 4 involve selecting and manipulating DOM elements using jQuery, the 5th adds interactivity to a responsive website footer with jQuery, and the 6th involves promises. Instructions are provided on organizing files.

Uploaded by

Haregewoyn Deyu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

jQuery and Asynchronous JavaScript (promise) Practice Exercises

The questions in here are based on the jQuery-Practice folder that contains an HTML file.
Please download the folder first from this link. Please look at the “Hint on how to organize
your folders and files” section below on how you organize your folders and files for this
practice.

The first two questions are the same questions you solved last week using vanilla JavaScript.
You will be using jQuery this time round.

Question 1:
The following three questions are based on the two paragraphs under the section which says,
"For Question 1".
1.1. Select the element with an id of "sample1" using jQuery.
1.2. Print the element itself on the console upon page refresh.
1.3. Print the content of the element on the console upon page refresh. Use jQuery to
select the content of the element

Question 2:
The following questions are based on the HTML code found under the section labeled "For
question 2".
2.1. Select the element with an ID of "techCompanies" and display it on your console.
2.2. How many tech companies are listed under the ul element with an id of
"techCompanies"?
2.3. Select all elements with a class of "red" and display them on the console.
2.4. Create a new li HTML element with a content of "Facebook" and display it on console
2.5. Give the newly created element a class of "blue" using jQuery
2.6. Append the newly created element next to the the "Sony" <li> element
2.7. How many of the tech companies are labeled blue? Find the result using jQuery and
display the result inside the "blueCompanies" div.

Question 3:
A form with two text fields is provided under the section which says "For question 3". Write a
jQuery code which takes the values of the two fields, checks if they are number values and
calculate the sum and average of the two numbers.
3.1. Display the result on the console
3.2. Display the result underneath the form
3.3. If any of the numbers provided is not a number, display a message that says "Please
enter numerical values only" underneath the form
Question 4:
Create an HTML form which asks users to provide their First name, Last name and Email
address. All the fields should be labeled as required. Once the user submits, write a JavaScript
function that checks if all the fields are provided. If not, it should show an error message above
the form.

If the user provides all the values, hide the form input fields, and display all the values provided
by the user on the browser.

Question 5: (Adding interactivity features on [Link] website’s footer section)


The following question is based on the responsive Apple website you built back in phase 1. As
we didn't cover JavaScript back then, we didn't implement some of the interactive features of
the website that are provided by JavaScript. You can use [Link]’s responsive code we wrote
from the link provided below to implement the interactivity of [Link]'s footer section.

Responsive code for [Link]:


● [Link]
You can refer to [Link]’s live website to check how the footer behaves:
● [Link]

In summary, the footer fully displays all the five columns in expanded state while viewed on
desktop or tablet size devices. You are required to implement the following mobile size
features.

Features on mobile size devices:


● Each of the five columns collapse to a single column. Make these columns collapse to
a single column.
● All the sub-links under each <h3> are hidden. Hide these sub-links
● There is also a newly added "+" sign on the right side of each <h3> to trigger the
expansion of the sub-links upon onclick event. Add the added "+" sign on the right
side of each <h3>. (Hint: everything up to this point can be achieved without using
any JavaScript at all. Bootstrap and CSS would be enough to achieve these).
● When users click on the "+" sign, the hidden sub-links under the respective <h3>
slide down and show. Then the "+" sign changes to the "x" sign. (Hint: Use jQuery to
implement the following feature)
● When users click on the "+" sign, the sub-links slide up and get hidden. Note: this
interactivity only happens on mobile size devices. (Hint: Use jQuery to implement
the following feature)
Question 6: on asynchronous JavaScript (promise)
● Visit the link here to find three quizzes. Please provide the output of the code for each quiz.
Please do not work on the quizzes online, rather create HTML and JavaScript files by
following the instructions below.

Hint on how to organize your folders and files

File organization for Questions 1 to 4


● Download the “jQuery-Practice” zipped file, extract it and save it under your
“Evangadi” folder. The zipped file contains the “jQuery-Practice” folder. Inside this
folder, you will find an “[Link]” file and a css folder containing a “[Link]”.
The document doesn't have the jQuery and your custom JavaScript files included on
it.
○ Inside of the ““jQuery-Practice” folder, create a folder called “js”.
○ Inside the “js”folder,
■ Create a JavaScript file called “[Link]”
■ Download the latest version of jQuery and save it under your "js"
folder.
○ Include/link both your “[Link]” and jQuery files at the bottom of your
“[Link]”. Note: Make sure you put your “[Link]” file below the jQuery
in your “[Link]”.
○ Just to make sure you have successfully loaded your “[Link]” file in your
“[Link]”, console the "jQuery Testing ..." message, check if you get the
message on your browser when inspecting.
● You will be writing your JavaScript code on the “[Link]” file.
● Now you can start working on your assignment. Happy coding!

File organization for Question 5


● The 5th question is based on the responsive Apple website you built back in phase 1
● All you need to do is download the “responsive-code-jquery-for-footer 2” zipped
folder from the link below, extract it and save it under your “Evangadi” folder.
○ [Link]
● Inside the “responsive-code-jquery-for-footer 2” folder, we have already included
for you:
○ A “[Link]” file
○ A JavaScript file, called “[Link]” where you write your JavaScript code
○ A “[Link]” file
○ A CSS file, called “[Link]” where you write your CSS code
● We have also included in the HTML document, the jQuery and Bootstrap library
links, the “[Link]”, “[Link]” and “[Link]” files for you
● All you need to do is write your JavaScript code in the “[Link]” and your CSS
code in the “[Link]”
Instructions on how to organize your folders and files for Asynchronous
JavaScript (promise) question
● In your Evangadi folder, create a folder, called “ asynchronousJavaScript”
● In your “asynchronousJavaScript” folder, create an HTML file called “[Link]”
● Include an HTML boilerplate in your “[Link]” file and give it a title of “Promise
Exercise”
● In your “asynchronousJavaScript” folder, create a JavaScript file called “[Link]”
● Link your “[Link]” file to your “[Link]”
● Before writing any code in your “[Link]”, make sure that your script file is linked to your
HTML file. To do that, type this code: alert("JS file linked!"); and run your HTML in your
browser
● Now, go to this link and copy the three quizzes on your “[Link]”. Do not copy the
multiple choice portions of the quizzes
● Now start determining the output of the code under each quiz. Note: When you determine
the output of the code, do not just guess the output. Please make sure you understand why
each line outputs whatever result it is outputting
● Now, open your “[Link]” file in browser, inspect and open your console to compare the
output you determined above with the output from showing on your console panel

Common questions

Powered by AI

jQuery, combined with CSS, allows for dynamic alterations to page layout and styling through event-driven JavaScript. On user actions, such as clicking a '+' icon, jQuery can add or toggle CSS classes that redefine styling rules. For instance, $('.expand').on('click', function(){ $(this).next('.content').toggleClass('expanded'); });, coupled with a CSS class '.expanded' having display:flex; or display:none;, changes the layout or visibility instantly. This integration enables responsive designs, like mobile collapsible sections, to be effectively managed with CSS transitions triggered by jQuery events.

Asynchronous programming, using constructs like Promises, underpins modern interactive web applications by enabling efficient handling of operations that take uncertain amounts of time—such as HTTP requests. Promises allow for non-blocking execution chains, improving performance and responsiveness. This means that user interface components, animated transitions, and data fetches run concurrently without halting page interaction. For instance, Promises enable fetching updated data from APIs while displaying static content or loader animations, only updating visuals when the promised data arrives, thus elevating user experience by seamlessly integrating data richness with UI fluidity.

You can use jQuery to select an element by its ID using the syntax $('#elementID'). To print the element itself, you can use console.log($('#elementID')); and to print its content, you can use console.log($('#elementID').html());. This approach allows you to understand both the jQuery selection method and methods to access element properties.

Key considerations include maintaining a clear folder structure, such as having separate folders for HTML, CSS, and JavaScript files. Files should be properly linked in HTML, placing script tags at the end of the body to avoid loading issues. For instance, ensure jQuery is linked before 'script.js'. Use descriptive naming conventions and comments within code for readability. Error handling should include checking console outputs, using commands like console.log('File loaded'), to verify successful loading. Employing such best practices ensures organized, traceable, and efficient debugging processes during development.

JavaScript libraries like jQuery simplify adding dynamic features by providing pre-built functions that handle common tasks with minimal code, thus reducing complexity. For responsive designs, jQuery can dynamically adjust layouts with methods like .toggleClass() to switch classes based on viewport size changes, triggered by $(window).resize(). Pre-packaged animations make interactions seamless, and event listeners handle user inputs efficiently. Using jQuery for cross-browser compatibility frees developers from manual JavaScript handling, enabling rapid prototyping and implementation of responsive features, enhancing development agility and maintaining code simplicity.

To implement error checking, iterate through input elements, checking each for a non-empty value using simple conditional statements. You could write a function like function validateForm() { let formValid = true; document.querySelectorAll('input').forEach((input) => { if (input.required && input.value.trim() === '') { formValid = false; document.querySelector('#error-message').innerText = 'All fields are required.'; } }); if (formValid) { document.querySelector('#error-message').innerText = ''; } return formValid; };. Using this function on form submission, any field left empty will prompt an error, ensuring completeness before processing.

jQuery simplifies form validation and user feedback by allowing developers to capture form submit events, validate data, and provide immediate feedback using concise syntax. For example, with $('form').on('submit', function(event){ ... }); developers can prevent form submission if validation fails, and use conditions to check input values, displaying messages such as 'Please enter numerical values only' with $('#message').text('Please enter numerical values only'). This ensures that user interaction is dynamic and responsive, handling both validation and UI updates efficiently.

jQuery offers cross-browser animation functions (e.g., .slideUp(), .slideDown(), .fadeIn(), and .fadeOut()) that maintain consistent behavior across browsers, thus improving user experience by ensuring reliability and performance. These functions enable interactive applications to provide smooth transitions for visual elements regardless of the user's browser. For instance, collapsing elements in a menu or footer can be animated with these methods, adding appeal through fluid transitions. Utilizing jQuery for animations supports broader browser compatibility compared to CSS alone, ensuring consistent behavior for all users.

Asynchronous JavaScript using Promises can enhance interactivity in DOM manipulation by deferring actions until certain events or conditions are met. For example, using Promise.resolve().then for an action upon clicking a '+' sign triggers hidden elements to slide down in jQuery. A promise can be applied like this: $(document).ready(function(){ $('.expandable').on('click', function(){ let promise = new Promise((resolve, reject) => { $(this).siblings('.content').slideToggle(); resolve(); }); promise.then(() => { $(this).find('.sign').text('-'); }); }); }); This approach defers UI changes like sliding animations until the user clicks an element, maintains a clean event cycle for UI updates and interactions.

Appending an element using jQuery involves creating a new HTML element and inserting it into the DOM at a specified position, which can be achieved using the append() method. For instance, $('<li>').text('Facebook').addClass('blue').appendTo('#techCompanies').next(); adds a new 'li' element next to the 'Sony' element. However, directly selecting and displaying an element's current status on the console using jQuery involves querying an existing element with a selector such as $('.red') and displaying it using console.log(). The core difference is that appending changes the DOM structure, while selecting merely retrieves the existing DOM state for display.

You might also like