Let's search for the secret rabbit script in the code

Can you try turning this exercise into a "rabbit catching" game where the rabbit moves when you hover over it? After 4 tries, display a message saying "No Easter Eggs". After 20 attempts, show "Humans Suck". Design the page with a single div element with fixed dimensions and a border. Add a p element underneath with an id for output purposes. Use the onmousemove event to count how many times the event was triggered and show the count in the p element. Here's a code snippet I tried:

<body>
<div>
 <h1>Catch the Easter Bunny to get your egg!</h1>
 <img src="rabbit.png" id="rabbit" onmouseover="MyFunction1()" alt="Catch the rabbit"/>
 <img src="rabbit.png" id="rabbit2" onmouseover="MyFunction2()" alt="Catch the rabbit"/>
 <img src="rabbit.png" id="rabbit3" onmouseover="MyFunction3()" alt="Catch the rabbit"/>
 <img src="rabbit.png" id="rabbit4" onmouseover="MyFunction4()" alt="Catch the rabbit"/>
 <h2 id="noeggs">No Easter Eggs for You</h2>
 <h2 id="yousuck">Humans suck!!!</h2>
</div>
<script>
 function MyFunction1(){
 document.getElementById('rabbit').style.visibility = 'hidden';
 document.getElementById('rabbit2').style.visibility = 'visible'; 
 // other functions omitted for brevity
 }

 // other functions omitted for brevity

</script> 
</body>

The above code worked but the task requires using a single function (not multiple ones like MyFunction1, MyFunction2, etc.) and having 20 different rabbits displayed. If caught within 4 tries, show "humans suck"; otherwise, if attempted more than 20 times, show "No Easter Eggs". I then attempted the following solution:

This is the html:
   <div>
  <p></p>
  <h1>Catch the Easter Bunny to get your egg!</h1>
  <img src="rabbit.png" id="r1" onmouseover="MyFunction()" alt="Catch the rabbit"/>
  <img src="rabbit.png" id="r2" onmouseover="MyFunction()" alt="Catch the rabbit"/>
  // more img elements...
  <h2 id="noeggs">No Easter Eggs for You</h2>
  <h2 id="yousuck">Humans suck!!!</h2>
  </div>
<script>

function MyFunction(){

document.getElementByTagNames('img').addEventListener('mouseover', onmouse);

// visibility settings for all img elements...

var code = document.querySelectorAll('img');

function onmouse(){
if(code == (document.querySelectorAll('img').style.visibility = 'visible')){
for(i = 0; i < code; i++){
code[i] = (int)(Math.random() * 20);
}
}
}
}
</script>

I've made several attempts, but even with hidden visibility, all my rabbits are still showing. I suspect issues with detecting arrays through querySelector('img') in my for loop. Additionally, I used a CSS file to hide certain messages with white text color. The addEventListener might also be problematic. Can someone please help me understand what's wrong with my script? I'd appreciate straightforward solutions rather than critiques of my coding style. Thank you!

Answer №1

The code initially worked well, but the task requires consolidating it into one function named MyFunction instead of spread across multiple functions like MyFunction1, MyFunction2, and so on, along with incorporating 20 different rabbit images.

Instead of the current setup:

function MyFunction1(){
    document.getElementById('rabbit').style.visibility = 'hidden';
    document.getElementById('rabbit2').style.visibility = 'visible';
    document.getElementById('rabbit3').style.visibility = 'visible';
    document.getElementById('rabbit4').style.visibility = 'visible';
}

You should modify the function to accept an input variable. Define your function like this:

function MyFunction(inputVar){

When calling the function later on, you will pass a value to it like so;

onmouseover="MyFunction(1)"

In this instance, the inputVar will be set to 1. If called as MyFunction(7), inputVariable would hold the value 7.

By introducing an input variable, the behavior of the function can be altered:

if(inputVar === 1){
    document.getElementById('rabbit').style.visibility = 'hidden';
} else {
    document.getElementById('rabbit').style.visibility = 'visible';
}

and so forth.

To resolve issues with your CSS effects, two main factors need addressing;

  1. Suspected typos in some function names. Such errors may trigger alerts; for verification, inspect the console within developer tools by hitting F12 on most browsers. In case of any error (like spelling errors), it will be highlighted in the console.

  2. Utilization of commands like document.get that return arrays in certain instances. A basic understanding of arrays is crucial. Implementing a for loop becomes necessary to iterate through each item in these arrays and apply the desired CSS styles.

I trust this information proves helpful to you. :)

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

"Conditional statement checks for the presence of a specific key in a JavaScript

While working on a MEAN stack project in Node.JS, I came across an interesting issue with a dictionary object. Earlier in my code, I created a dictionary named keywordSearches. It holds information about the frequency of keyword searches, pulled from Mong ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

Transferring information to modal without using AngularUI

I'm currently working on an Angular application and facing an issue with passing data from my controller to a modal. Here is the HTML code on my index page: <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> ... </head> & ...

I'm confused as to why my external CSS file isn't cooperating with Bootstrap 4

I am facing an issue with loading an external CSS file into my index.php. I have placed the external CSS file at the end of all other CSS files like bootstrap and font awesome. However, when I try to make changes to the design using the code in the externa ...

How can I apply justify-content exclusively to the first row with Bootstrap 4?

I need a solution where the rows generated dynamically within a div are centered only if it is the first row. If there is only one row and the elements in that row do not fill up to the specified Bootstrap class properties col-xl-3 col-lg-4 col-md-6 col-sm ...

Struggling with making /api/login/ function properly - using JavaScript and Reddit

Oh no, I've reached my limit of attempts... just received the message "you are doing that too much. try again in 27 minutes." So, I decided to come here and seek help. Here is the request I am making URL: http://www.reddit.com/api/login/ Headers: ...

Unit tests manipulating JavaScript functions to return undefined values

Currently, I am in the process of testing some JavaScript functions within a larger React application. These functions heavily utilize the module pattern, which leads me to believe that my misunderstanding lies within this pattern. The script I am testing ...

HTML elements not connected to each other

Despite having the correct code for linked objects, social media buttons are not functioning as links: <li class="facebook" title="" data-placement="bottom" data-toggle="tooltip" data-original-title="Facebook"> <a href="https://www.faceb ...

Unable to hyperlink in a div containing the my-auto class in Bootstrap

I am facing an issue with my carousel layout. I have 3 columns, and one column is reserved for Prev & Next carousel controls. These controls are vertically aligned using the my-auto class. However, after adding this class to the column, the links within it ...

Using regular expressions in JavaScript, we can separate a paragraph into individual sentences

Hey there! I'm currently working on a project that requires extracting sentences from a paragraph using regex in JavaScript. Unfortunately, my attempts to achieve this have resulted in syntax errors as I have tried methods used in other programming la ...

The multi-level dropdown feature in the BootStrap-4 navbar extends off the screen when the dropdown menu is opened

I have been struggling to make this work. I used BS4 for responsiveness, and my navigation items are aligned to the right in the navbar. Despite trying various methods to position the submenu on the left of the parent menu, I still can't get it to dis ...

What is the best way to send JavaScript data to PHP?

Is it possible to post a variable to a PHP script without refreshing the page? If so, how can this be achieved? Here is an example using jQuery: $.ajax({ url: "myphpfile.php", type: "post", data: json/array/whatever, success: function(){ ...

A data table created with Bootstrap is not displayed inline with the pagination feature

Customizing Bootstrap Data Table Code Instructions on how to customize this code: <div class="row"> <div class="col-sm-5"> <div class="dataTables_info" id="example_info" role="status" aria-live="polite"> Showing 1 to 10 of 2 ...

What is the best way to modify attributes within HTML content that is dynamically generated by a script?

I'm currently implementing a widget script from a federated search service: <script type="text/javascript" id="s9f5b2bb09b74013279b22ae8d1b2df50" src="http://uleth.summon.serialssolutions.com/widgets/box.js"></sc ...

Selecting either "THREE.NearestFilter" or "THREE.LinearFilter" will result in the black plane

During my experimentation with the THREE.js library, I encountered a notification stating: THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. To address this issue, I made the ...

Browser resize affects the overlap of DIVs

I've seen similar posts before, but I believe the issue with my website (***) is unique. At full size, the website looks exactly how I want it to. However, when I resize the browser window, the text ("ABOUT INTERNATIONAL PARK OF COMMERCE.." and below ...

Cloud function -> time stamps evaluation

I've been working on a cloud function to delete items in the "links" collection that have an end time older than the current timestamp. Although my function runs without any errors, it's not deleting the items as expected and is causing me quite ...

Apply CSS styling to the v-html output

I am trying to enhance the style of HTML code using a v-html but have been struggling with finding a working solution so far. Can anyone help me out? :( Below is my code snippet: Template : <div class="para" v-html="value" /> Script : exp ...

Improve the nested async callback in the componentDidMount() function of a React component by moving it to a separate

My current approach involves utilizing react's componentDidMount(), which contains a substantial amount of code and performs two callbacks. Eventually, within the innermost callback (the second one), I trigger this.setState({}). Simplified Code clas ...

Better ways to conceal notifications as soon as a new one appears with Toastr

Whenever a new notification pops up in my application, I desire for the previous one to automatically disappear. It is crucial for only one notification to be displayed at any given time. Is there a way to accomplish this using toastr? ...