Is there a way to verify the location of an element?

Currently, I am attempting to monitor the position of the 'car'. When the car reaches a top offset of 200px, I would like to apply a specific property to the 'phone' element. The concept is that as you scroll down, the car will move, and when it aligns with the phone, the phone should flash.

I have implemented an If statement, but there seems to be an issue that I'm unable to pinpoint. Can someone assist me with this?

$(window).scroll(function () { 
    // You've scrolled this much:
  var newSize = $(window).scrollTop()/20;
  var srotate = "translateY(" + newSize + "px)";
  $('.car').css({top:newSize,"-moz-transform" : srotate, "-webkit-transform" : srotate});
    
  if($('.car').css('top') == '195px') {
      $('.phone').css('box-shadow', '1px', '1px', '17px', '4px', '#42ab9e');
    }
});
.he {
  height:4000px;
  overflow-x: hidden;  
}
.car{
  right:20px;
  position:fixed;
  margin-top:20px;
  display:block;
  z-index:0;
}
.car img {
      width: 40px;
  }
.phone {
  display:block;
  position: absolute;
  top: 1950px;
  z-index:1;
  padding-right: 6px;
  right:0px;
}
.phone img {
    width:67px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="he container"></div>
<div class="car">
   <img src="http://www.image-maps.com/m/private/0/nai005qun3o0h9r81e0ndpvrh6_car.png" alt="car">
</div>
<div class="phone">
  <img src="http://www.image-maps.com/m/private/0/nai005qun3o0h9r81e0ndpvrh6_phone.png" alt="">
</div>

Answer №1

If you're looking to pinpoint the exact location of an element, HTML 5 Canvas is your go-to solution. By leveraging Kinetic-js, not only can you easily draw objects on canvas, but you can also retrieve the coordinates when those objects are dragged around. The beauty of using Kinetic js lies in its ability to provide accurate coordinates, giving you the freedom to implement any desired functionality with ease. I trust this information proves useful to you.

Answer №2

To fix your issue, you can easily determine the car's distance from the top of the screen. (Additionally, your jquery code for adding css seems to be faulty)

if($('.car').offset().top >= 195) {
    $('.phone').css('box-shadow', '1px 1px 17px 4px #42ab9e');
}

Subsequently, you can utilize this method to apply a class to your phone or any other element. Checking the top position of the car component may not provide accurate results. It is recommended to check its offset from the top of the screen in pixels, since the output will be a float value. Additionally, ensure that you compare if the car's position is equal to or higher than the specified threshold, as only checking for equality might lead to unexpected behavior.

Feel free to explore the console in the modified example and observe the outcomes: https://jsfiddle.net/L2pf7cmu/

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

Traverse a subsection of an extensive array in Java

In my Java Boggle game project, I have a method that goes through all possible combinations of a randomized board and checks each one against a dictionary list to verify if it is a valid word. If the word is valid, it is added to the key. While this method ...

There seems to be an issue with rendering or redirecting in Jade files, the routes folder, and server/app.js

//routes/meal.js var express = require('express'); var router = express.Router(); var app = express(); /* GET users listing. */ router.get('/meal', function(req, res, next) { res.render('/home/noah/Desktop/gadfit/views/meal.jad ...

Select2 isn't functioning properly, consistently showing the message "No results found" every time

After exhausting all options on this platform without success, my goal remains unchanged: to extract state data from a JSON file generated by a servlet and then present the information in a dropdown menu using AJAX. However, no matter what I input into th ...

"You have an undefined error with 'Navigator.' Check out the JSHint before using the forecast API that utilizes JSON

I'm tasked with creating a small app prototype for a school assignment that interacts with the Forecast.io API. While I don't have much experience working with APIs, the code seems clean and functional. However, within Brackets, JSHint is flaggi ...

Guide to customizing the layout preview specifically for certain components in Storybook, without affecting all components

Currently working on my storybook project and facing an issue. I'm aiming to have the layout centered in the preview section. I attempted export const parameters = { layout: 'centered', }; in the .storybook/preview.js file However, this c ...

What is the process for immediately changing the background color of an input field as soon as text is entered?

I am encountering an issue with the code snippet provided below. My goal is to change the background color of an input field as soon as I start typing something into it. The scenario involves 4 input fields where if the submit button is clicked and any f ...

Implement event listeners to transcluded content in AngularJS

How can I add event handlers to transclusion content in a directive without allowing consumers to add their own click handlers? I want the directive to handle it, but I'm unsure of the correct approach for adding handlers to the content passed with ng ...

Struggling with validating forms with JavaScript

I'm having trouble with the following JavaScript code: <script type="text/javascript"> function checkDetails(search) { var search = documment.getElementById('query'); if(search.value ==''||search.val ...

Implement a horizontal scrollbar for your table in HTML

I need to implement a horizontal scroll bar for my table. Here is the HTML code: Even though I have utilized Bootstrap, the horizontal scroll bar is not working for this particular module. It works fine in other modules. The tbody data is added after an ...

Choose All Box for Dynamic Tables in AngularJS

Hi everyone, I'm currently working on adding a select-all checkbox to the top of my list of checkboxes using a custom directive. I found some guidance on how to do this in a thread that I came across: https://github.com/lorenzofox3/Smart-Table/issues/ ...

What is the best way to pass default event argument alongside another argument in React?

This snippet demonstrates the function I wish to call when a certain input type is invoked: _handleOnEnterPress = (e, receiverUserId) => { if (e.keyCode === 13) { // assuming keycode 13 corresponds to 'enter' console.log("pressed ...

What is the best way to remove every other second and third element from an array?

I am looking to remove every second and third element of an array in Javascript. The array I am working with is as follows: var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"]; My goal is to delete every second and ...

Encountered issue while converting half of the string array to JSON using JavaScript

I encountered an issue with the code below while trying to convert an array into JSON. Here is my code: <html> <head> </head> <body style="text-align:center;" id="body"> <p id="GFG_UP1" style="font-size: 16px;"> </p ...

What is the best way to show search suggestions on Google Maps autocomplete once three characters have been entered?

While integrating google-maps into my react app, I encountered an issue with the autocomplete feature. I would like the location search to display options only when at least 3 keys are entered, but Google maps autocomplete starts showing options with jus ...

Error: Unable to locate module: '@material-ui/core/Breadcrumbs'

Recently, I incorporated React's Material UI into my project and attempted to integrate the Breadcrumbs component. However, I encountered an error message stating: Cannot resolve '@material-ui/core/Breadcrumbs'. I have already installed @m ...

How to define an index signature in Typescript that includes both mandatory and optional keys

I am on a quest to discover a more refined approach for creating a type that permits certain keys of its index signature to be optional. Perhaps this is a scenario where generics would shine, but I have yet to unlock the solution. At present, my construc ...

Change the right border style for the second and third ToggleButtons in the ToggleButtonGroup

I've been working on this for a few hours now and I can't seem to get it right. Currently, I'm using Mui v5 and trying to style the ToggleButtons to look like regular MUI buttons. So far, I was able to achieve this transformation: https:/ ...

My jQuery form is not functioning properly upon initialization

Let's take a look at this sample 'template' code: $(document).on("<EVENT>", "form", function() { $(this).find(".input input").each(function() { var required = $(this).attr("required"); var checkField = $(this).clos ...

Troubleshooting issue with SQL delete statement - unable to delete a recipe with the specified recipe_id

Developing a functionality to delete data. I am currently working on removing a particular recipe by its unique identifier, which is the recipe_id. The issue I encountered is that when I send the request to delete using the handleDelete function in my bac ...

Impeccable method to safeguard element from external css interference

Currently, I am working on a script that will be utilized across various pages and I want to ensure that the elements it generates are not affected by the CSS styles of those pages. Some individuals suggest using CSS like this: body>*{min-height:200px; ...