How do I convert a passed String to a jQuery Object?
HTML
<img id="gamePaddle" src="Game_1_Support/images/king.gif" alt="paddle" />
Here's my JS -- I call doFade("#gamePaddle")
function doFade(objectID) {
// var theObject = document.getElementById(objectID);
// alert(typeof objectID === 'string' || objectID instanceof String); // true
// alert($(objectID)) // [object Object]
$(objectID).fadeOut(3000);
} // doFade
I have also tried hard-coding and failed:
$("#gamePaddle").fadeOut(3000);
Obviously, I am doing something wrong and my hunch is that it's very basic -- I need some help here, if you please.
CodePudding user response:
Please try this :
function doFade(objectID) {
// var theObject = document.getElementById(objectID);
// alert(typeof objectID === 'string' || objectID instanceof String); // true
// alert($(objectID)) // [object Object]
$(objectID).fadeOut(3000);
} //
doFade('#gamePaddle')
https://jsfiddle.net/2nuo83cm/
CodePudding user response:
This works for me. Are you sure you have included jQuery properly, and do you call the function in either document.ready or another event listener?
function doFade(objectID) {
$(`#${objectID}`).fadeOut(3000);
}
$(document).ready(function() {
doFade('gamePaddle');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="gamePaddle" src="https://cdn.pixabay.com/photo/2019/07/30/18/26/surface-4373559_960_720.jpg" alt="paddle">