How can you use Jquery to hide an element when clicking on a DIV?

I'm currently developing a JavaScript with jQuery script that displays a div block when the countdown timer reaches zero.

Check out my code snippet:

<HTML>
<HEAD>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="./test.css" />
<script>
$(function () {
var count = 5,
    countdown = setInterval(function () {
        $("p.countdown").html(count);
        if (count == 0) {
            $("p.countdown").hide();
            $("p#countblock").show();
            clearInterval(countdown);
        }
        count--;
    }, 1000);
});

$('#clickToHide').click(function() {
        $("p#countblock").hide();
    });
</script>
</HEAD>
<body>

<p id="clickToHide"> X </p>

<p class="countdown"></p>

<p id="countblock"> text to appear </p>
</body>
</HTML>

And here's how I styled it using CSS:

#countblock{
    display:none;
    width:200px;
    height:50px;
    position:absolute;
    background-color:#f1f1f1;
}

The functionality seems to be working fine, but for some reason, clicking on "X" isn't hiding the countblock. Can you help me identify where I went wrong and provide a solution?

Answer №1

Your code appears to be correct, but it may not be functioning as expected due to its current placement. It is positioned before the body tag, so you will need to utilize $(document).ready(); or relocate the code to the footer of your page.

Answer №2

add an event listener for click once the DOM is loaded

  <script>
    $(function () {
        var number = 10,
        timer = setInterval(function () {
            $("p.timer").html(number);
            if (number == 0) {
             $("p.timer").hide();
            $("p#blockTimer").show();
            clearInterval(timer);
         }
          number--;
       }, 1000);
  });
  </script>

<body>

  <p id="hideOnClick"> Hide Me </p>

  <p class="timer"></p>

 <p id="blockTimer"> text will be displayed </p>

 <script>     
   $('#hideOnClick').click(function() {
         $("p#blockTimer").hide();
     });
  </script>

Answer №3

Tested out a jsfiddle and everything seems to be running smoothly. It's possible that there might be a timing issue: the JavaScript is being loaded before all of the HTML elements are fully loaded. You should try using $( document ).ready

$(document).ready(function() {
     // place your code here
});

Take a look at this functioning example: http://jsfiddle.net/4RtYh/7/

Answer №4

Here's how it operates, check it out

$(function () {
var count = 5,
    countdown = setInterval(function () {
        $("p.countdown").html(count);
        if (count == 0) {
            $("p.countdown").hide();
            $("#countblock").show();
            clearInterval(countdown);
        }
        count--;
    }, 1000);
});

$('#clickToHide').click(function() {

        $("#countblock").hide();
    });

Answer №5

Swap the contents of the head and body:

<body>
<button id="clickToHide"> X </button>
<p class="countdown"></p>
<p id="countblock"> text to appear </p>
<script>
$('#clickToHide').click(function() {
   $("#countblock").hide();
});
</script>
</body>

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

Ignored CSS hover effect on touch screen devices

I've added a new div with an HTML button: $('.nav').append('<button class="restart">Restart</button>'); This button has some CSS properties for hover effects. However, I am facing an issue where on touch-screen device ...

jQuery is throwing an error indicating a missing closing parenthesis after the argument list

By using the code snippet below, I am able to add a new row to my table (#courseelements). $("#addbutton").click(function() { $('#courseelements > tbody:last').append('<tr><td>Helloworld</td></tr>'); ...

HTML and CSS: Centering elements inside div containers

Is it possible to align elements within a </div> using the align attribute? For example, as shown in the image below: e1:align="top" e2:align="right" e3:align="bottom" e4:align="left" EDIT: This query is purely for self-learning purposes in HTML ...

What is the reason behind the majority of marketing tags (like Omniture, XE, etc) being implemented using document.write()?

Could this be a Repeat: Why use document.write? Despite the drawbacks of using document.write(), why do most tracking and marketing tags still utilize it? I have pondered this question extensively, and the only reasonable explanation I can think of i ...

How can I assign a background image to a specific state or template using AngularJS?

While attempting to style the entire template with a CSS div tag, I encountered an issue. The code snippet used was: <div ng-style="{'background-image': 'url(/images/food.png)', 'background-repeat': 'repeat-y'}"& ...

Utilizing Shadertoy's iResolution variable within a Three.js code snippet

Currently, I am in the process of converting a mesmerizing shader effect from Shadertoy into a local Three.js project. Despite my efforts, I have been struggling to get it to render properly. If you'd like to give it a shot yourself, you can access th ...

Retrieving Dropdown Value in Bootstrap 5: How to Obtain the Selected Item's Value from the Dropdown Button

I am having a slight issue with my dropdown button where I am trying to display the selected item as the value of the dropdown button. The Flag Icon and Text should be changing dynamically. I have tried some examples but it seems that it is not working as ...

Unexpected behavior observed when executing JavaScript Promise.all code

My current issue involves retrieving data from a mySQL DB by using the following code. Within the database, there are multiple tables including an Activity table with a channelId field, a Channel table with a userId field, and a User table with a userName ...

Develop a JavaScript application that contains a collection of strings, and efficiently sorts them with a time complexity of O(nlog n)

Seeking assistance in developing a JavaScript program that contains an array of strings and must sort them efficiently in O(nlog n) time. Grateful for any guidance... ...

Using jQuery, implement a functionality where a line break is added when the Enter key is pressed. Furthermore, the added

I have a text box where users can add cars to a list. Each car is entered on a new line, and when the user presses enter, jQuery adds a \n to move to the next line. However, when I collect this string, the \n characters are "hidden" and cannot b ...

How do you incorporate a basic if statement within a td tag in PHP?

My PHP script contains an if statement that retrieves the last index of ',' in a string: if($idx = strripos($output,','))//Get the last index of ',' in your output string { $ErrorCode = substr($output,$idx + 1,(strlen($outpu ...

Having trouble executing the JavaScript file after rendering it through Rails

Having an issue with my Ruby (1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]) on Rails (3.2.6) application: I am trying to execute a js file, but it only prints without executing. View: 291 <%= form_for :change_top_ten, remote: true, ...

Learn the art of closing an AngularJS accordion automatically when another accordion is opened within an AngularJS application

I have encountered an issue with the AngularJS accordion functionality. It seems that when I have multiple accordions, such as accordion-1, accordion-2, and accordion-3, they all open simultaneously if clicked on individually. My main concern is: How can ...

Steps for assigning a 404 status code upon promise rejection

My approach to testing the login functionality involves using promises and chaining them. If the user enters an invalid password, the data is rejected; otherwise, it is resolved. I then verify if the user is logged in successfully by chaining these methods ...

Automatically resize iframe height to fit content

There are numerous solutions available for dynamically changing the height of an iframe. I recently tested out a plugin called https://github.com/house9/jquery-iframe-auto-height Although the plugin does adjust the iframe height upon initial load, it fall ...

How can refs be applied effectively in React applications?

I've been thinking about the role of refs in React and how they can address certain challenges for developers. However, I have found that the explanations provided in the React documentation are not very clear, and there seems to be a lack of helpful ...

Retrieving selective attributes from Cosmos DB NoSQL using NodeJS/Javascript: Exploring the readAll() method for retrieving specific attributes instead of the entire object

Imagine having the following set of documents in your Cosmos DB (NoSQL) container: [ { "id": "isaacnewton", "fullname": "Isaac Newton", "dob": "04011643", "country": &q ...

Analyzing the elements in a 2D matrix against those in a 1D array

I'm currently working on developing a trivia game for my class, and I've run into an issue where I need to compare the values of a single index in a 2-dimensional array with a value from another array. Despite using an if statement for comparison ...

Creating infinite dynamic name selectors: A step-by-step guide

Having redundant jQuery calls is something I'm dealing with, and I would like to streamline them using a loop. $('.class1').on('click', function () { ... $('.class2').on('click', function () { ... $('.clas ...

Attach a 20% image to the top that remains visible while scrolling

I am working with a Bootstrap Modal Window that includes: An image and a scrollable list of comments related to the image (scrollable with overflow:auto). The Modal window also contains an Add comment Textarea at the bottom. I am looking to implement th ...