Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display the value of a jQuery variable for testing?

I am working on a slider that uses jQuery. Some elements of the slider are working correctly, but there is a problem that I am trying to troubleshoot with some of the code. To test it I would like to be able to display the values of the variables in the statement.

Here is the code block I am working with:

$('.marquee_nav a.marquee_nav_item').click(function(){
        $('.marquee_nav a.marquee_nav_item').removeClass('selected');
        $(this).addClass('selected');

        var navClicked = $(this).index();
        var marqueeWidth = $('.marquee_container').width();
        var distanceToMove = marqueeWidth * (-1);
        var newPhotoPosition = (navClicked * distanceToMove) + 'px';
        var newCaption = $('.marquee_panel_caption').get(navClicked); 

        $(' .marquee_photos').animate({left: newPhotoPosition}, 1000);
        });

I added a div called 'test' where I would like to display the values of the variables to make sure they are returning expected results:

<div class="test"><p>The value is: <span></span></p></div>

For example, to test the values, I inserted this into the statement above:

$('.test span').append(marqueeWidth);

However, I don't get any results. What is the correct way to include a test inside that code block to make sure I am getting the expected results?

Thanks.

like image 404
forrest Avatar asked Oct 15 '13 13:10

forrest


Video Answer


3 Answers

Just use JavaScript's console functions to log your variables within your browser's console.

var myVar = 123;
console.log(myVar, "Hello, world!");

Example Console Image

If you're unsure how to open the console within your browser, see: https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers

like image 164
James Donnelly Avatar answered Sep 17 '22 20:09

James Donnelly


append is used to append either an HTML string, a DOM element, an array of DOM elements, or a jQuery element. Since you are just trying to show a number (marqueeWidth), you probably want to set the text of the span instead:

$('.test span').text(marqueeWidth);

Also, is there a particular reason why you don't just use the console? It may be worth reading over a Debugging JavaScript walkthrough.

like image 39
jbabey Avatar answered Sep 20 '22 20:09

jbabey


you can use the following.

$('.test span').html(marqueeWidth);

However doing a console.log(yourvariable); or alert(yourvariable); is better.

like image 45
sudhAnsu63 Avatar answered Sep 19 '22 20:09

sudhAnsu63