I have a small click script that works when a button is clicked. I cant seem to figure out after googling and reading numerous stackoverflow question and answers how to run my script in the browser console. It seems from what I gathered to type the function and parameter followed by a semicolon. But I cant get it to trigger that way. Here is my script -
$(".cta").click(function() {
$("html, body").animate({ scrollTop: $("#footer").offset().top }, 500);
console.log('executed scrollToElement');
return true;
});
What do I need to type to run it in the console? This is killing me that I cant seem to figure this out. I am pretty novice with jQuery and Javascript. I have been reading some of the Sitepoint recommended books. And even doing some other stuff. But working with the console is a bit tricky it seems in it self. Am I right or wrong?
Hi there,
Given the following page:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>A very boring page</title>
</head>
<body>
<button id="myDiv">Click me!</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</body>
</html>
If you open it in your browser (Chrome for me) and click on the button, nothing happens.
Then if you open the console by presisng F12 -> Console.
Then copy paste the following code:
> $("#myDiv").on("click", function(){ alert("Yay!"); });
Note: it can be on multiple lines, no problem.
You should see:
[<button id=​"myDiv">​Click me!​</button>​]
Now if you click on the button you will see an alert.
Note: You very probably don’t need the return true
in the code you posted.
Thanks for the reply, I also didnt think about I had a wrapper around the function. And it wasnt globally accessible. Noob problems. But I do want to add another animation to this. If I want an element to bounce after the first function is finished running how would I add that to my code? I found a few examples on stack overflow. But couldnt seem to put it together with this.
When you animate something using the jQuery library, you have the opportunity to specify a callback, which is run when the animation finishes. This can of course be another animation.
This should illustrate the point:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Animate with callback</title>
<style>
header{ background: red; height:500px; }
div{ background: blue; height: 5000px; }
footer{ background: yellow; height: 500px; }
</style>
</head>
<body>
<header></header>
<div></div>
<footer></footer>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$("body").animate({ scrollTop: $("footer").offset().top }, 3000, function(){
alert("Done");
});
</script>
</body>
</html>