0

I am fairly new to programming in general. Recently, I have started learning jQuery and I have tried making a little 'game' with it. However, I can not find an answer anywhere on how to make a jQuery object trigger a JavaScript event.

My code is:

    <!DOCTYPE html>

    <head>
        <title></title>
        <link href='stylesheet.css'/>
        <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
        <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
        <script>
        confirm("Are you ready for your race?")
var snd = new Audio("rev1.mp3");
snd.play();

$(function() {
$("#car").draggable();
});
        </script>
    </head>
    <body>
        <div id="car">
            <div id="top"></div>
            <div id="bottom"></div>
            <div id="fwheel"></div>
            <div id="bwheel"></div>
        </div>
        <div id="line">
        <div id="line1"><img src="#"></div>
        <div id="line2"><img src="#"></div>
        </div>
    </body>
</html>

What I am trying to do here is when the object (which is the div id 'car') reaches 'line2', an alert pops up and a sound plays, but I am not sure how to make that happen.

Thanks in advance.

kappa322
  • 27
  • 2
  • 5

3 Answers3

0

Try adding line2 as droppable

http://plnkr.co/edit/yDMZdXLUc4FV5lMrNYsM?p=preview

  $(function() {
    var hasReached = false;

    $("#car").draggable();

    $("#line2").droppable({over: function(){
      if(!hasReached){
        alert("Tada!!!");
        hasReached=true;
      }
      console.log("over line 2");
    }})

  });
mccainz
  • 3,478
  • 5
  • 35
  • 45
0

You can even track the x and y co-ordinate of the draggable div

$('#car').draggable(
    {
        drag: function(){
            var offset = $(this).offset();
            var xPos = offset.left;
            var yPos = offset.top;
           //check it is over the line and show alert
        }
    });
Ajay Narain Mathur
  • 5,326
  • 2
  • 20
  • 32
-1

You could probably use the same answer than the one given here:

How do I trigger the Drop event with jQuery UI Droppable without actually dragging and dropping?

$("#droppable").droppable({
        drop: function(event, ui) {
            do stuff }
    }); var drop_function = $("#droppable").droppable.option('drop'); drop_function();
Community
  • 1
  • 1
Daniel Forbes
  • 624
  • 3
  • 10