Add the onclick function to $(document).ready for applying the desired functionality

I've been trying to create a fading effect for 3 divs on my page, similar to the one in this example: http://jsfiddle.net/x4qjscgv/6/ However, I want the fade animation to trigger only when a user clicks a button. I attempted to use the document.getElementById function but it doesn't seem to be working as expected.

Below is the complete code snippet:

<html>

<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>

$(document).ready(function() {
  $('.word1, .word2, .word3').each(function(fadeIn) {
    $(this).delay(fadeIn * 500).fadeIn(1000);
  });
});

document.getElementById('btn').onclick = function(e)

</script>

<style>
    #chat {
      display: none;
    }
</style>

</head>

<body>

<button id="btn"> Fade Divs </button>

<div id="chat" class="word1">Word 1</div>
<div id="chat" class="word2">Word 2</div>
<div id="chat" class="word3">Word 3</div>


<div id="" class="">Word 4</div>

</body>

</html>

Answer №1

Feel free to take inspiration from my approach. Remember, an id is unique while a class can be used for multiple elements!

$(document).ready(function() {
    $('.word1, .word2, .word3').each(function(fadeIn) {
        $(this).delay(fadeIn * 500).fadeIn(1000);
    });
});
  
$("#btn").on('click', function(e){
    $('.word1, .word2, .word3').each(function(fadeIn) {
        $(this).delay(fadeIn * 500).fadeIn(1000);
    });
});
$("#btnhide").on('click', function(e){
    $('.chat').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<style>
.chat {
    display: none;
}
</style>
</head>
<body>

<button id="btn"> fade divs </button> <button id="btnhide"> hide divs</button>
  
<div class="chat word1">Word 1</div>
<div class="chat word2">Word 2</div>
<div class="chat word3">Word 3</div>
  
  
<div id="" class="">Word 4</div>
</body>

Answer №2

Although this line selects #btn, it does not execute properly because the function declaration is incomplete:

document.getElementById('btn').onclick = function(e)

To make it work, you need to include the actions of the function like this:

document.getElementById('btn').onclick = function(e){
    // add functionality within curly braces.
}

Remember that the variable e represents the Event object. Try adding console.log('test') and then check the console (usually accessed via right-click > "Inspect") for your output messages.

Answer №3

It seems that the onclick function you used is not functioning as intended because you did not enclose your fade-in code within it. If you are already utilizing jQuery, consider using the click event handler, like this:

$(document).ready(function() {
    $('#btn').click( function () {
        $('.word1, .word2, .word3').each(function(fadeIn) {
            $(this).delay(fadeIn * 500).fadeIn(1000);
        });
    });
});

Answer №4

Revise your demonstration:

<div id="chat1" class="term">Term 1</div>
<div id="chat2" class="term">Term 2</div>
<div id="chat3" class="term">Term 3</div>

.term {
  display: none;
}

$(".term").click(function(e){
    $(this).delay(10).fadeOut(1000); 
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for manipulating observableArray information retrieved through the $.getJSON method

Recently, I've started using knockout.js and I'm really enjoying it so far! While working in MVC4, I encountered a small issue. I had successfully implemented kojs with static data, but now I need to work with data passed from a controller via JS ...

What is the best way to insert a JavaScript variable into a filter while using ng-repeat?

I'm currently working on a situation where I have the following code: <div ng-repeat="i in MediaFeedItems | filter: { category: 'userSelect' }" class="mediafeed--item"> This specific code snippet is responsible for iterating through ...

The function is trying to access a property that has not been defined, resulting in

Here is a sample code that illustrates the concept I'm working on. Click here to run this code. An error occurred: "Cannot read property 'myValue' of undefined" class Foo { myValue = 'test123'; boo: Boo; constructor(b ...

The Facebook Customer Chat Plugin embedded within an iframe

Can the Customer Chat Plugin be used within an iframe? When adding content-security-policy: frame-ancestors IFRAME_DOMAIN, it displays the message Refused to frame 'https://www.facebook.com/' because an ancestor violates the following Content Se ...

Enable the ability to input a value of -1 by clicking on a button or link, but only allow it once (the first click) without needing to disable the button or

I am working with the following script: <script language=javascript> function process(v){ var value = parseInt(document.getElementById('v').value); value += v; document.getElementById('v').value = valu ...

Creating a task list without using JavaScript in the web browser and without relying on a database

Looking for some guidance on building a todo app for a job interview where JavaScript is disabled in the browser and no database can be used. Any JavaScript needs to be handled on the server side. I have some basic knowledge of node/express and serving H ...

Is there a way to automatically shorten a text when it goes beyond the boundaries of a div container?

How can I prevent a paragraph in one of two adjacent div containers from having a line break without changing the container's size? The surrounding div uses display: flex to position its children side by side. Currently, I've applied the followin ...

Issue with JQM popup functionality in Firefox browser

I am currently utilizing JQM 1.3.1 and have a webpage featuring various popups located at the bottom of the page: <div data-role="page" data-title="Strategic Plans"> <div data-role="content" id="capbPlans" data-bind="cafeLiveScroll: { callbac ...

Creating dynamic form fields in Flask WTForm based on user's previous selection is a useful feature that can be achieved with some

I am interested in developing a form that dynamically generates different text area fields based on the selection made in a dropdown menu beforehand. Specifically, the idea is to create projects of various categories where, for instance, if a user chooses ...

Once you address a block using jQuery

$(function(){ $(window).scroll(function () { var scrollVal = $(this).scrollTop(); var adscrtop =$(".header").offset().top // 在 RWD 767以下不作動 if(window.screen.width>767){ if(sc ...

A Vue computed property is returning the entire function instead of the expected value

One of my computed properties is set up like this: methods: { url_refresh: function (id) { return `${this.url_base}?start=${Date.now()}` } } However, when I attempt to print the value on mount: mounted() { console.log(this.url_refresh) ...

What steps can be taken to avoid triggering ng-drop-success upon clicking?

Here is an example of a div with Angular directives: <div ng-drop="$ctrl.activateDropArea" ng-drop-success="$ctrl.onDropComplete($data,$event)"> However, I am facing the issue where the onDropComplete function gets called even when I click on the d ...

Python Ordering menu items for the Pelican restaurant

In response to jcollado's advice on this thread, I have set up my menu as per his instructions. However, I am facing difficulty adding the active CSS to the active item. DISPLAY_PAGES_ON_MENU = False DISPLAY_CATEGORIES_ON_MENU = False MENUITEMS = ( ( ...

Creating 3D models in three.js

Working with a 3D point cloud data in three.js, I have successfully added points to a Geometry using Vector3. Now I am looking to create surfaces from these points. for(var key in dt) { var hole = dt[key]; var pX = hole['x'] - planeMinX; var pY ...

HTML or JS/jQuery can create disorienting cursor behaviors

Is there a way to create a distorted or crooked mouse movement on a webpage, even though the user is moving the mouse normally? I'm exploring ways to simulate the experience of a Parkinson's or arthritic patient trying to navigate a web page wit ...

How to efficiently remove duplicate items from multiple select dropdowns in Angular using ng-repeat?

Need help with dynamically assigning objects to select boxes in AngularJS. I have a scenario where I add multiple select boxes to a form, but each box should only display items that haven't been selected in other boxes. How can I achieve this functio ...

Managing asynchronous tasks that do not save their outcomes within the application state

Upon discovering a requirement within a vanilla JS webapp that necessitates a single JSON "definitions" object for rendering, I realized that the definitions are to be loaded through an HTTP request at the start, then read, parsed, and passed down to anoth ...

Does the padding attribute get passed down in CSS?

Hi there! I've been working on the following code snippet: .blah { padding: 15px; background:green; } .blah div{ background:red; } <div class='blah'> <div> foo </div> & ...

Is there a method to navigate through nested JSON accessors without prior knowledge of the nested keys? The table is encountering an error

How to Handle Nested JSON Accessors in React Table Without Knowing Keys const columns = Object.keys(data).map(key=>{ return { Header: key, accessor: key } }); <ReactTable ...

Using only native JavaScript Vanilla, Rails does not execute create.js via Ajax

Concerning Rails 4 and Vanilla JavaScript, I encountered an issue with my code for creating a Shop record via Ajax. The record is successfully created, but the create.js file is not being triggered as expected. A strange occurrence happens in Chrome where ...