Learn how to iterate over an array and display items with a specific class when clicked using jQuery

I have an array with values that I want to display one by one on the screen when the background div is clicked. However, I also want each element to fade out when clicked and then a new element to appear. Currently, the elements are being produced but they do not disappear or fade in. I am using jQuery for this purpose and I am still getting the hang of it!

$(document).ready(function(){
        var arr = ["hello", "hi", "what is up"];
        $.each(arr, function(i, val){
            $("#background").click(function(){
            var element = "<h1>" + val + "</h1>";
            $(".contain").fadeIn("slow").append(element);
            $(element).remove();
            });
      });
    });

Answer №1

It's efficient to only set the callback function once:

$(document).ready(function(){
    var arr = ["hello", "hi", "what is up"];
    var i = 0;
    $("#background").click(function(){
        var element = $( "<h1 style='display:none'>" + arr[i] + "</h1>" );
        $(".contain").html(element);
        element.fadeIn("slow")
        i =(i+1)  % arr.length;
    });
});

HTML

<body>
<div id='background'>  <div class="contain">  click me  </div> </div>
</body>

Click here to see it in action.

Answer №2

The concept behind this code snippet is to display each element from an array one at a time in a circular manner. The counter keeps track of the elements displayed and resets once all elements have been shown. You'll need the following code :

HTML :

<div id="background">
  <div class="contain">
    <div></div>
  </div>
</div>

CSS:

#background {
  height: 500px;
}

.contain {
  height: 200px;
  background-color: #ccc;
}

jQuery :

$(document).ready(function() {
  var arr = ["hello", "hi", "what is up"];
  var currentKey = 0;
  $("#background").click(function() {
    //alert("CurrentKey : " + currentKey);
    $(".contain").html(" " + arr[currentKey] + " ").hide().fadeIn(600);
    if (currentKey === (arr.length - 1)) {
      currentKey = 0;
    } else {
      currentKey = currentKey + 1;
    }
  });
});

You can run the snippet below to see this :

$(document).ready(function() {
  var arr = ["hello", "hi", "what is up"];
  var currentKey = 0;
  $("#background").click(function() {
    //alert("CurrentKey : " + currentKey);
    $(".contain").html(" " + arr[currentKey] + " ").hide().fadeIn(600);
    if (currentKey === (arr.length - 1)) {
      currentKey = 0;
    } else {
      currentKey = currentKey + 1;
    }
  });
});
#background {
  height: 500px;
}

.contain {
  height: 200px;
  background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="background">
  <div class="contain">
    <div></div>
  </div>
</div>

For those who prefer JS Fiddle, here's the JS Fiddle link.

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

Unexpected value detected in D3 for translate function, refusing to accept variable

I'm experiencing a peculiar issue with D3 where it refuses to accept my JSON data when referenced by a variable, but oddly enough, if I print the data to the console and manually paste it back into the same variable, it works perfectly fine. The foll ...

Is it beneficial to incorporate AJAX functionality into my PHP classes and scripts?

I recently started working on a PHP/AJAX website and I'm contemplating the best approach to "only include the content". Should I incorporate if statements in my header and footer scripts to check for a "ContentOnly" get parameter? Then, append that p ...

Clicking on the initial link will in turn prompt clicks on the subsequent links

Can you please provide instructions on how to correctly simulate a click on the remaining links if a click is made on the first link? jQuery('a.one_num').click(function() { jQuery('a.two_num').click(); jQuery('a.three_num&ap ...

Angular 6 - Consistently returning a value of -1

I'm facing an issue with updating a record in my service where the changes are not being reflected in the component's data. listData contains all the necessary information. All variables have relevant data stored in them. For example: 1, 1, my ...

Develop a JSON structure by retrieving nested documents using Firebase Firestore and Express

I'm currently working on developing an application using Express and Firebase Cloud Functions. I'm facing a challenge in creating a nested JSON structure based on the database schema specified below: Below is the code snippet that I am using: ex ...

Access information from a service

I have developed a new service named servcises/employees.js: angular.module('dashyAppApp') .service('employees', function () { this.getEmployees = function() { return $.get( '/data/employee.json' ); }; }); ...

Top method for gathering user information on a webpage, showcasing it on the page without disrupting the overall layout

As I work on developing a web application, one feature involves displaying a chart sourced from a database for users to interact with and answer questions. Once the user submits their answers, I want to showcase both their responses and suggested answers o ...

Instructions on extracting the ID value from a specific field by utilizing a text box autocomplete feature

This is the code snippet I utilized for implementing auto complete functionality: Within the HTML View: <script> $(function () { $("#autoComp").autocomplete({ source: '@Url.Action("GetAutoComp")', ...

Is there a way to use JavaScript to alter the existing URL?

Currently, I am utilizing a select tag to allow users to choose the number of 'rows' displayed on the table. <%=select_tag :per_page, options_for_select([10,20,50,100]....some more code...., onchange => "if (this.value) {windows.location=& ...

Steps for incorporating the count() value in Django for web developmentTo embed the count() value while creating

I'm currently working on a web visual board project using Django. Here is the specific HTML section where I need to populate values from the database: <tbody> {% for obj in data_list %} <tr> <th>{{ ob ...

Ways to assign the value of an alert to an element

Within this piece of code, my intention is to retrieve the alert value and apply it to an element. Description: The AJAX code I have written checks for values in a database, fetches new values from the database, and then displays these fetched values in a ...

Retrieve the initial image link from a blogger's post in cases where it is not being stored on the Blogger platform for use in related

I am currently using a hosting service to store the images that I include on my blogger platform. However, I have encountered an issue where blogger does not automatically fetch the image url to use as the thumbnail when the image is hosted externally. C ...

How can I ensure that my style.scss file effectively interacts with my stylesheet by including imports for "variables", "globals", and "header"?

Currently, I am in the process of learning how to utilize Sass and JavaScript through VS Code. Within my project structure, I have an "app" folder where my js folder resides containing script.js, as well as a scss folder holding _globals.scss, _header.scss ...

Using Javascript to organize an array of objects based on a specific condition

Having an array of objects structured as follows: obj = [{'name': 'Tom', 'age': 17, 'gender': 'male', 'color':'red', 'position':3}, {'name': 'Sam', ...

Tips for maintaining a fixed size for CSS grid cells' minimum and maximum dimensions

I am attempting to utilize CSS grid to create an entirely fixed layout. This layout is for an embedded application that contains both GUI elements and text fields. The sizes of the cells should remain unchanged and not readjust as their content grows or sh ...

What is the reason behind the Placeholder not functioning in IE8?

Whenever I trigger the onblur event on an input of type "password", it will hide both the placeholder text and the input itself. Check out the GitHub link for this plugin ...

Ensure that a div with fluid width remains consistently centered within another div

I have a bunch of boxes filled with content. The number of boxes in each row varies depending on the width of the browser window. Is there a way to ensure that all the boxes are always horizontally centered on the page? For guidance, you can check out th ...

Establishing a universal function within Ionic AngularJS

I have the following code snippet, where I have added a reset function that I want to be able to use from ng-click in any part of any template. angular.module('starter', ['ionic', 'starter.controllers', 'starter.services ...

Leaving a message on someone else's Facebook wall by sharing a link to a website

I've been trying to figure this out, but I honestly have no idea where to start. Twitter has a feature that allows a link to open a box where users can write a tweet and post it directly to their chosen feed: It's really simple, just changing t ...

How can Request.UrlReferrer be configured using client-side JavaScript? If it can be done, what is the process?

In my application, I heavily rely on Request.UrlReferrer to handle link clicks and maintain a page history for users. Due to new requirements, I now need to navigate to a specific location using <input type="button" /> instead of <a href="mypage. ...