0

I have this jquery code, working 100%. This is executing on every page load, when i import my js file in the html. My question, how can i make use of this code, only when the element is present, or call it directly from the element itself? I have similiar functions, but, on html's that dont have specific elements, javascript execution halts. Sometimes because the html elements dont exist on that specific html file.

/**
* Message Box Display
*/
$(document).ready(function() {
$("#Message-Box" ).slideDown("slow", function() {
    $("#Message-Box").addClass('Show');
    setTimeout(function(){
        $('#Message-Box').addClass('Hide');
    }, 5000);
});
});
2
  • 2
    There shouldn't be a problem. jQuery will not throw an error when no elements on the page matches the selector. When you say "JS execution halts", can you clarify what has exactly happened? Do you get any error messages in your browser console? Commented Aug 12, 2014 at 19:17
  • if($("#Message-Box").length > 0) Commented Aug 12, 2014 at 19:19

2 Answers 2

1

try something like this

$(document).ready(function() {
  var msgbx = $("#Message-Box");
    if (msgbx.length) {
        msgbx.slideDown("slow", function() {
            msgbx.addClass('Show');
            setTimeout(function() {
                msgbx.addClass('Hide');
            }, 5000);
        });
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

The function halting my script was this one:

/**
 * Background-Audio
 */
$(document).ready(function() {
   var audioTrack = document.getElementById("Background-Audio");
   if(audioTrack)
   {
    audioTrack.volume = 0.05;
    audioTrack.play();
   }
});

1 Comment

My fix, was adding the if. Error was something of cannot change volume attribute on a null element. That was happening on all the pages that dont have the audio html tag. Thats why the others jquery etc, were not running on them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.