javascript if condition not executing properly

I am struggling with my random number generator that should generate numbers between 5 and 15. I am trying to change the position of the 'chest' div based on the number generated by the computer, but for some reason it is not working as expected. I have double-checked that the div is named 'chest', there is a CSS statement for 'left', and the function is indeed being called and generating a number.

Below is the code snippet:


var xChestPosition;
var yChestPosition;
function randomNumberForChest(firstNum, secondNum) {
    xChestPosition = Math.floor(Math.random() * secondNum) + firstNum;
    yChestPosition = Math.floor(Math.random() * secondNum) + firstNum;
    alert(xChestPosition);
    
    switch (xChestPosition) {
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
        case 10:
        case 11:
        case 12:
        case 13:
        case 14:
        case 15:
            $('#chest').css('left','300');
            break;
        default:
            // Handle other cases
            break;
    }
}

Answer №1

To ensure accuracy in CSS positioning, it is advisable to always specify the unit of measurement.

$('#chessboard').css('left', '300px')

Answer №2

It is suggested to utilize the following code snippet for optimal results:

$('#chest').css({"position": "absolute", "left": "300px"});

Instead of using:

$('#chest').css('left','300');

This is because specifying the position attribute is crucial when setting the left attribute, whether it's absolute, fixed, or relative. By doing so, your conditional statement will be executed accurately.

Answer №3

Give this code snippet a try:

let xPositionOfTreasure;
    let yPositionOfTreasure;

    function generateRandomPositionForTreasure(minNum, maxNum) {
        xPositionOfTreasure = Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum;
        yPositionOfTreasure = Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum;
        
        alert(xPositionOfTreasure);
        
        switch (xPositionOfTreasure) {
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
            case 11:
            case 12:
            case 13:
            case 14:
            case 15:
                $('#chest').css('left', '300px');
                break;
            default:
                // Do something else
        }
    }

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

``What is the best way to adjust the layout of

I've been using the CSS code below to center items on my page: #MainBox { width: 488px; height: 181px; position: absolute; left: 50%; top: 236px; margin-left: -244px; //this being half the width } However, when viewing the pag ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

positioning a text input in the center instead of at the top of the page

Hello everyone, I am just starting out with HTML and I have a question. How can I make the Username: <input type="text" name="Username" style="- margin-top: 200px;"> appear in the center of the page instead of at the top? I've tried changing the ...

Pressing the Button Increases the Counter, However the Counter Resets After

My goal is to create a basic counter with increment and reset buttons. When I click on the increment button, the counter properly goes from 0 to 1 (I can confirm this by checking the console log in Chrome). The issue arises when, after incrementing, the c ...

Integrating Dart with external libraries

Here is a straightforward example demonstrating the usage of a map library: <!doctype html> <html> <head> <script src="http://api4.mapy.cz/loader.js"></script> <script>Loader.load()</script> </head; &l ...

Using the if-else statement in an email form: A step-by-step guide

I have successfully created an email form, but now I want to enhance it by adding options for the subject field. If the subject is set to cancel, then a cancel message like your service is cancelled should be displayed in the Message (body) field. On the o ...

Event follows activation of trigger click

I've already gone through this post on Stack Overflow about triggering an action after a click event, but none of the solutions I've tried so far have worked. Let's say I have a menu on my webpage like this: <ul class="nav nav-tabs"&g ...

Encountered an issue when attempting to access a file on the desktop using Node.js

Here is the code I am using to read a simple file from my desktop: module.exports = function (app) { app.get('/aa', function(req, res) { fs = require('fs'); fs.readFile('â€ĒC:\\Users\\t5678 ...

Creating a JavaScript function that increments or decrements a variable based on keyboard input is a useful feature

My goal is to have a count start at 100 and then either count up or down by 1 when a specific keyboard button is pressed. Currently, I am using the keys 8 and 2 on the keypad, which represent ascii numbers 104 and 98. So far, the code I have only allows f ...

What causes setInterval to create an endless loop when used inside a while loop in JavaScript?

I attempted to initiate a delayed "one" call or a "one or two?" question, but instead of working as expected, the function continued running indefinitely. Surprisingly, everything worked perfectly fine without using setInterval. quester2() function quest ...

"Utilize Meteor to transmit emails to internal email addresses within the intran

I have successfully developed a Meteor App to manage requests. However, I am facing an issue where I need emails with default text to be sent whenever a request is created or updated. The challenge lies in the fact that I am operating within an intranet e ...

Transforming multi-layered form data into a JSON array structure for seamless integration with application/json

I'm currently developing a Laravel application and facing an issue with the $controller->wantsJson() method in the back-end. This method returns TRUE only if the content type of the request is set to application/json. jQuery.ajax({ type: ...

Is it possible to efficiently utilize Map/Set in TypeScript/JavaScript when working with objects?

I'm currently transitioning from Java to TypeScript and I've encountered an issue with working with objects in hashmaps and hashsets. In Java, I would simply override the hashCode method to easily manipulate these data structures. Is there a simi ...

Difficulty accessing `evt.target.value` with `RaisedButton` in ReactJS Material UI

My goal is to update a state by submitting a value through a button click. Everything works perfectly when using the HTML input element. However, when I switch to the Material UI RaisedButton, the value isn't passed at all. Can someone help me identif ...

Leverage the power of jQuery and AJAX in conjunction with the Laravel framework to showcase and

I am currently working on a page that showcases various products. Initially, I had set up a route as follows: Route::get('products/{category}/{subcategory}') In my controller, I was returning results from the database to display the items. Howe ...

Reducing the number of DOM manipulations for websites that heavily utilize jquery.append

Here's a snippet of my coding style for the website: !function(){ window.ResultsGrid = Class.extend(function(){ this.constructor = function($container, options){ this.items = []; this.$container = $($container); ...

All menus effortlessly sliding out simultaneously

I'm having an issue with my navigation bar. I want each link to slide its corresponding DIV up or down when clicked. However, all the DIVs are sliding and when clicking on the same link everything slides up. How can I fix this problem? This is my HT ...

Illuminate XHR 500 (Server Side Issue)

I'm currently troubleshooting an issue with this AJAX script, but I'm unable to identify the specific problem. The Chrome developer tools are indicating a "500 (Internal Server Error), doWork @ (index):16 , onclick @ (index):28" Is there anyone ...

"Implementing filtering logic for an array of objects with multiple conditions in a React application

I am looking to apply filters to a person list based on criteria such as city, job, age, and gender. How can I apply filters based on five conditions in React? I tried using filter chaining but it did not work for me. In the useEffect hook, I applied indiv ...

What is the best way to initiate an AJAX request and retrieve the requested data?

How do I set up my ajax function? $(function() { $("form#new_user").click(function(e) { e.preventDefault(); var dataString = $('#new_user').serialize(); $.ajax({ type: 'POST', url: '/user', da ...