简体   繁体   中英

How to develop jQuery drag and drop with sound effect?

I need to create jQuery drag and drop. when I drop item should make sound, dose anyone know how to do it? I know we can do it with HTML5 audio tag with CSS and jQuery to make it happen but I need a sample code in order to modify it.

$(function() { $( "#draggable" ).draggable();

// need sound in my droppable

    $( "#droppable" ).droppable({
        drop: function( event, ui ) {
            $( this )
                .addClass( "ui-state-highlight" )
                .find( "p" )
                    .html( "Dropped!" );
        }
    });
});

// my code

   $("div#gameboard div").droppable({


        drop: function (event, ui) {
            {

                sendMessage("m " + this.id + " " +
                                 localToGlobal(imgID) + " " +
                                 $(ui.helper).css("left") + " " +
                                 $(ui.helper).css("top")

                            );


            }

           myAudio.src = 'audio/song.mp3';
        }
    });

I may not be perfectly right but here is some thing that can help you maybe:

var myAudio = document.createElement('audio');
myAudio.controls = true;
myAudio.src = 'Your File';
myAudio.play();

To make it works when you drop, you can create the audio tag before and just hit play() every drop.

I would initialise the audio tag in the ready function:

$(document).ready(function() {

}

Then user your code:

$( "#droppable" ).droppable({
    drop: function( event, ui ) {
        $( this )
            .addClass( "ui-state-highlight" )
            .find( "p" )
                .html( "Dropped!" );

        myAudio.play();
    }
});

});

I had to put the code outside of the $(document).ready(function() to get it working in my application:

    <script>
var myAudio = document.createElement('audio');
myAudio.controls = true;
myAudio.src = 'audio/beep.mp3';
myAudio.src = 'audio/beep.wav';
//myAudio.play();
</script>

Then you simply trigger the myAudio.play(); inside your drop: function code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM