Wasim Karani
Wasim Karani

Reputation: 8886

Using jQuery in a JavaScript function

function divlightbox(val)
{
    if(val)
    {
        val=val.replace( /^\s+/g, "" );
        var count_js=0;
        var big_string='';
        document.getElementById("video_lightbox").innerHTML="";
        document.getElementById("divlightbox").style.display = "block";
        $("#video_lightbox").css({"height":"430px","top":"10%","width":"480px"});

I found out that the error is in the above. My question is can't I use jQuery and traditional JavaScript at same time? I have done coding like this numerous times and never ran into a problem like this. I used to use jQuery methods like .hide() and .css() inside JavaScript functions but this time it doesn't work.

Thanks in advance.

Upvotes: 9

Views: 65252

Answers (4)

majick
majick

Reputation: 319

While the other answers fix the specific problems, I don't think the OP's question (in bold) is really answered here, as depending on the specific context, $ may possibly not be defined as a jQuery object yet (having had this problem myself a few times now.)

In which case you would need to do something like:

function divlightbox(val) {
    // ...
    // just use jQuery instead of $ one time
    jQuery("#video_lightbox").css({"height":"430px","top":"10%","width":"480px"});
}

OR

function divlightbox(val) {
    // define the $ as jQuery for multiple uses
    jQuery(function($) {
        // ...
        $("#video_lightbox").css("height":"430px");
        $("#video_lightbox").css("top":"10%");
        $("#video_lightbox").css("width":"480px");
    }); 
}

Upvotes: 16

fcalderan
fcalderan

Reputation:

You must provide error in javascript console.

1) Do you pass a val argument to divlightbox function()? When do you call it?

2) why do you use the same identifier divlightbox both for a function and for a div id? Change name to the function please, maybe the problem could be here.

3) Always check if video_lightbox and divlightbox exist before accessing them.

Upvotes: 1

Z. Zlatev
Z. Zlatev

Reputation: 4820

jQuery is JavaScript so YES. Instead .innerHTML="" just use .empty(). Instead .getElementById() use $('#..') and so on.

Upvotes: 5

Patricia
Patricia

Reputation: 7802

to do things like hide(); and css() you need jquery objects. you can't do them to dom elements.

so you could do $('#video_lightbox').html(""); or

$('#video_lightbox').empty();

Upvotes: 4

Related Questions