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

Comparing Yii's CHtml::link() function with the use of regular <a href=''></a> HTML tags

When using elements like yii CHtml::link, what are the recommended practices? I'm working on a button that needs to include an icon, text, respond to hover events, and be wide. Are there any benefits to using CHtml instead of a regular tag that can e ...

navigate back to the previous tab using protractor

When I open a new tab (second), I attempt to switch back to the first tab. common.clickOpenNewSession(); //opens a new tab browser.getAllWindowHandles().then(function (handles) { var secondWindowHandle = handles[1]; var firstWindowHandle ...

How to place a child <div> within a parent <div> that is fixed on the page

I am currently working on creating a modal window using HTML/CSS. My goal is to have the modal window fixed in position relative to the browser window, with a white background. Inside the modal, there will be an image at the top and a div element at the bo ...

Having trouble retrieving an object through a GET request in Node.js with Express

Currently, I am going through a tutorial on Node.js by Traversy Media and I have encountered an issue that has me stumped. The problem arises when I attempt to retrieve the response of a single object from an array of objects using the following code: app ...

What is the process of exporting a module that has been imported in ES6?

Here are 3 code snippets: // ./src/index.ts const myApp = { test: 1, ... } export default myApp // ./src/app.ts import myApp from './src/index' export default myApp // ./index.vue import { example } from './src/app.ts' console.l ...

Mocha struggles to locate the ID within an input field - react-native

I am attempting to retrieve the text of an input using the .text() method in Selenium. However, every time I try to locate the element, it says that the specified ID was not found. (I am working with the Input component from NativeBase, but I have also te ...

Tips for navigating through a webpage by scrolling

My goal is to automatically scroll down to the bottom of the page and then perform a specific action. With the help of uiautomator, I was able to retrieve the following information: index=2, resource-id=com.manoramaonline.arogyam:id/pager,class=android.sup ...

The function to navigate, 'navTo', is not defined and so it cannot be read

I am trying to create a navigation button in my SAPUI5 application deployed on Fiori _onPageNavButtonPress: function () { var oHistory = History.getInstance(); var sPreviousHash = oHistory.getPreviousHash(); if (sPreviousHash !== ...

Discover how to initiate an ajax request from a tailored module when the page is loaded in ActiveCollab

When trying to initiate an AJAX call on the project brief page by adding a JavaScript file, I encountered some issues. My goal is to display additional information along with the existing project brief. I included a JavaScript file in a custom module and f ...

Is it possible for me to set my HTML body class as ".body" in CSS?

CSS .body { background: linear-gradient(-45deg, rgb(255, 0, 0), rgba(216, 29, 29, 0.856), #fdfdfdd7, #234cd5, #ffffff); background-size: 400% 400%; background-repeat:no-repeat; animation: gradient 35s ease infinite; height: 100vh; } HT ...

Phonegap application functioning smoothly on computer, encountering issues on mobile device

Hey there! I recently developed a phonegap app that retrieves JSON data from a YQL link and presents it to the user. It works perfectly on Google Chrome desktop, but my client mentioned that it doesn't work on his Android 2.3 device. Could you help me ...

Transform your image using the Bootstrap framework

I am attempting to create a similar banner using bootstrap. You can view the demo of the banner here. https://i.stack.imgur.com/JXLNY.png I'm struggling to understand how to achieve this in bootstrap 3 and where to begin. Should I use rows and colum ...

Position the division at the location of the cursor for particular usemap components

Looking for a way to position a division on top of an image using a usemap. Interested in having the div only appear when the mouse hovers over a particular area, and at the precise location of the cursor. Came across some examples using jQuery, similar ...

What is the best way to conceal the initial column using jquery?

Is there a way to automatically hide the first column of data as it loads from a csv file using jquery and AJAX? I know you can do this using onclick function, but I prefer to have it automatically hidden. How can I achieve this? Below is the sample CSV d ...

javascript creating unique model instances with mongoose

I've searched through related posts without finding exactly what I need. Currently, I am working on building a backend rest API and conducting tests to collect data. Each test has its own model which is associated with collections in the database. T ...

The table disappears when there is no data available in the database

One of my challenges involves a table that displays data retrieved from a database. The code for this is as follows: <table class="table table-hover table-bordered" style="width:300px" id="contact"> <tbody data-bind="foreach:items"> ...

Execute JavaScript/AJAX solely upon the selection of a button

Currently, my script is being executed immediately after the page loads and then again after a button click. Is there any way to modify it so that the script waits until I click the button before running? As far as I understand, this code runs asynchronous ...

Tips for setting up my ajax/views method to output a dictionary

Here's the HTML snippet I have along with an AJAX request: <script> $("#search_button").on("click", function(){ var start_date = $("input[name=\"startdate\"]").val(); var end_date = $("input[name=\"end ...

Which option provides the highest level of efficiency in terms of selector

After working with jQuery, I am curious about the speed of different selectors but I'm not sure how to go about testing them. I've learned that using an id selector like $("#xxx") is the fastest and most efficient option. But what about $("img[d ...

What is the best way to pass an email as a Laravel parameter within a function using Angular?

I'm currently working on a feature that allows users to delete their account only if the input field matches their email address. However, I encountered an error: Error: $parse:lexerr Lexer Error when attempting to set this up. Here is my HTML code: ...