Naming a function that loads on document ready - javascript

I have got a .js file that adds functionality to a menu when the page loads (when document is ready) ... the first three lines of the file are...
( function( $ ) {
$( document ).ready(function () {
$('#cssmenul li.has-sub>a').on('click', function(){
After that there's loads more code that adds colours and other visual effects.
At the moment the function doesn't have a name - it just runs. However if I wanted to call the function from a button how do I name it? If called the function activateMenu I would then have a button like this:
<input type="button" value="Activate" onclick="activateMenu();">
Thanks very much

If you want to reuse the code as activateMenu, then you can group the contents of that code into its own function and reference it inside your .ready()
(function($){
$(document).ready(function(){
activateMenu();
});
})(jQuery);
function activateMenu(){
console.log('test');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="activateMenu()">Test Button</button>

create your function separately and the just pass the reference of it to the ready event, like this,
function doSomething(){
// do whatever you want to do
console.log('doing something')
}
// then
$( document ).ready(doSomething)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="doSomething()">click me</button>

Related

Function not working when using $( document ).ready on external js file

I have a simple button that calls a function inside index.html, and the function itself is in script.js, the function works when not using $( document ).ready(function() { //...}); but as soon as I add this line (at script.js), it won't work. This is how it looks:
index.html:
<button onclick="myFunction()">Click</button>
script.js with $( document ).ready: (Not working)
$( document ).ready(function() {
function myFunction(){
alert("Alright!");
}
});
script.js without $( document ).ready: (Working)
function myFunction(){
alert("Alright!");
}
Jquery solves this problem using selectors and binding events
In this cas use $('button').click(); to listen when the button is clicked.
Remove inline onclick
Hope this helps :>
$( document ).ready(function() {
$('button').click( () => alert("Alright!"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
You must have to add a library of JavaScript called jQuery. Because you are using the syntax of jQuery. (A rich and powerful JavaScript Library)
in Vanilla JavaScript we use document.getElementById('btnSubmit')
But in jQuery we write $('#btnSubmit') to do the same thing.
That's why you need to use the jQuery Library. You can use it directly form cdn or you can download it offline.
If you want to use cdn just add this
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script>
One more thing in jQuery we use
$(document).ready(function(){
//your code goes here
})
to make sure that the Script will be effective after the DOM parsing/rendering is completed.
Thank you.
Another option is that u can create a variable outside of the document.ready scope. Probably, not your best option, but will get job done.
var func;
$(document).ready(function(){
func= function()
{
alert('Alright!');
}
});
<button onclick="func()">Click</button>
The scope of the anonymous function in$( document ).ready() no longer available when the execution of the function is finished . So can't call the function from this scope.
That happen because when the HTML is loaded onClick attribute is readed but this function is still not loaded.
The best approach in this case is make the binding on ready event.

How to click a button element on page load

I have created 5 buttons. I'm loading some pages on button click. I want the first button automatically clicked on page load and load it's corresponding html file and the remaining buttons should load html files only on clicking them. Someone help me!!
This is my jquery:
$('a#Home').click(function() {
$("#home").load("x.html");
});
$('a#Menu1').click(function() {
$("#menu1").load("y.html");
});
$('a#Menu2').click(function() {
$("#menu2").load("z.html");
});
$('a#Menu3').click(function() {
$("#menu3").load("searcharray.html");
});
$('a#Menu4').click(function() {
$("#menu4").load("sortarray.html");
});
Just test this code. I think this will help you.
$( document ).ready(function() {
console.log( "ready!" );
$('#btn1').trigger( "click" );
});
function fun1()
{
alert('loaded');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1" onclick="fun1()">btn1</button>
<button id="btn2">btn1</button>
<button id="btn3">btn1</button>
<button id="btn4">btn1</button>
trigger the event yourself:
$('a#Home').click(function() {
$("#home").load("x.html");
});
$('a#home').trigger('click');
Theoretical answer
You can trigger any event on any element using the .trigger() method. This will require you to specify which event you want to fire. More information.
It is also possible to trigger a click event just by calling .click() after binding the event handling. The documentation shows us that we can use this function for both purposes.
$( document ).ready() is an interaction that can be used to run code once when the document has been loaded. More info on that can be found here.
Examples
Example #1 (using .trigger())
$( document ).ready(function() {
$('a#Home').trigger('click');
});
Example #2 (using .click())
$( document ).ready(function() {
$('a#Home').click();
});
Assuming the first button is Home then you want run that on document ready by using $(function()
<script>
$(function() {
$('a#Home').click();
});
function loadHome() {
$("#home").load("x.html");
};
</script>
Then update your link to be like:
<a id="Home" onclick="loadHome()">Click Me</a>
You can try this:
<script>
function pageLoad()
{
alert('hello');
}
pageLoad();
</script>
<button id="btn1" onclick="pageLoad()">btn1</button>

trouble with jQuery lifecycle

index.html:
<input type="text" id="inputs" name="inputs">
<input type="button" id="btnAdd" value="submit">
script.js:
(function() {
function myFunction(input) {
alert(input);
}
$('#btnAdd').click(myFunction($('#inputs').val()));
});
I'm having trouble getting my javascript to run when my button is clicked. I assume I am misusing the ready function or my page has yet to register the button, but I am unable to break at any linein the javascript when I debug the page. Can someone tell me the proper way to get this to function? Thanks.
Because of the way it's written, the code you provide for script.js would never run. You probably want to put your function into a call to jQuery so it gets executed when the DOM is loaded.
Also, you need to wrap your click callback inside an anonymous function, or else it will execute myFunction when you're trying to add the callback instead of on the actual click.
$(function() {
function myFunction(input) {
alert(input);
}
$('#btnAdd').click(function() {
myFunction($('#inputs').val())
});
});
https://jsfiddle.net/9du8rxw0/
you need to add callback to your click event and for $(document).ready(function(){ }) the short hand is $(function(){ }).and it is better to write custom functions outside of document ready.
$(function() {
$('#btnAdd').click(function() {
myFunction($('#inputs').val())
});
});
function myFunction(data) {
alert(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inputs" name="inputs">
<input type="button" id="btnAdd" value="submit">
Adding a $ before your self-invoking function will tell jQuery to wait for the entire page, including your myFunction definition to load prior to execution.
like
$(function() {
function myFunction(input) {
alert(input);
}
$('#btnAdd').click(myFunction($('#inputs').val()));
});
then make sure either myFunction is declared in global scope, or better yet, wrap within your self-invoking function as well.
You need the $ in front of (function(), and your click function needs curly braces.
$(function() {
function myFunction(input) {
alert(input);
}
$('#btnAdd').click(function(){myFunction($('#inputs').val())});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" id="inputs" name="inputs">
<input type="button" id="btnAdd" value="submit">
I'm guessing that the DOM is not yet loaded, and that your attempt to shorthand the call to .ready() is erroneous. Try prefixing with $:
Also, your event handler setup is not doing what you want.
// Need $ before your parens (shorthand for .ready())
$(function() {
function myFunction(eventData) {
alert(eventData.inputValue); // <-- get input value from eventData
}
// This is not proper usage of .click()
// https://api.jquery.com/click/
// $('#btnAdd').click(myFunction($('#inputs').val()));
// You want to pass the relevant eventData as the first param,
// and a reference to your handler in the second.
$('#btnAdd').click( { inputValue: $('#inputs').val() }, myFunction);
});
Although, if you don't need myFunction to be defined separately, you might be better off with #Gerasimos' suggestion.

JQuery : Removing DOM objects that have been added in load()

File contents are given below. I have a button, "load_button", whose click event triggers a load() function. The html file loaded with the function contains another button, "my_button". The callback of the load() function adds a handler for the click event of "my_button". The problem is, every time I press "load_button", a new click event handler is added, and the alert in the event handler pops up multiple times. I want to delete previously created "my_button" with its event handler, before creating the new one. What I tried is adding the following command, where its commented out in the file descriptions below.
$('#page').empty();
No luck. I wanted a general solution, since I'll have other DOM objects to be removed. How can I remove them?
Also, it does not work when I replace
$('#page').on('click', '#my_button', function () {
with
$("#my_button").click(function() {
Why isn't it working? Isn't the callback function of load() supposed to be run after the loading is done, and DOM objects are available?
main.html
<html>
<head>
...
<script src="main.js"></script>
</head>
<body>
...
<a id="load_button">Load!</a>
<div id="page">
</div>
</body>
</html>
1.html
<div>
<a id="my_button">Go!</a>
</div>
main.js
$(document).ready(function(){
$('#load_button').click(function() {
// $('#page').empty();
$("#page").load('1.html', load_scripts());
});
});
function load_scripts() {
$.getScript('script.js');
}
script.js
$(document).ready(function(){
$('#page').on('click', '#my_button', function () {
// $("#my_button").click(function() {
alert('COWABUNGA!');
});
});
It looks like you don't need to load scripts dynamically at all. Try a main.js that looks like this:
$(document).ready(function(){
$('#load_button').click(function() {
$("#page").load('1.html');
});
$('#page').on('click', '#my_button', function () {
alert('COWABUNGA!');
});
});

Toggle text with function called with onclick

my question is a short one but I couldn't figure it out by myself. I've got a function like -> http://jsfiddle.net/gtU56/ . I'm calling a javascript-function with an event-listener(onclick) in my html-code. The function itself is more complex but I need the last snippet. By clicking 'Show More' the text should change. Why won't the text change?
Because the toggleText function isn't available when the html code is rendered.
In other words the function isn't set until the page is ready so the onclick function doesn't reference anything.
Either have the function like here http://jsfiddle.net/gtU56/2/
or have it in the head of the page because its needs to be ready immediately
If you want it to wait for the ready state you can do the following and remove the onclick action all together
http://jsfiddle.net/gtU56/7/
$(".text").click(function()
{
$(".text").toggle();
});
toggleText = function () {
$('.text').toggle();
}
check here http://jsfiddle.net/gtU56/3/
It's because of how you're loading the function. Switch it from onLoad to no wrap (head) and it works fine.
jsFiddle example
Using jsFiddle's onLoad wraps your function in a window.onload call like this:
<script type="text/javascript">
//<![CDATA[
$(window).load(function(){
function toggleText() {
$('.text').toggle();
}
});//]]>
</script>
While no wrap (head) just adds it normally like this:
<script type="text/javascript">
//<![CDATA[
function toggleText() {
$('.text').toggle();
}
//]]>
</script>
since you are already claiming having jquery, you need not use inline javascript. try this
var elems = $('.text');
elems.click(function(){
elems.toggle();
});
fiddle : http://jsfiddle.net/gtU56/5/
$('.text').click(function() {
$('.text').toggle('slow', function() {
// do your animation..
});
});
​
Js Fiddle
This is the solution - http://jsfiddle.net/gtU56/6/
You need to first make sure that the function is registered after page load. Then, bind a click event to the div.
Hope this helps!
First you should organize you jQuery code like this:
$.(document).ready(function() {
// enter jQuery code here
});
Otherwise you're accessing a not completly loaded html document.
Also, you don't need the event-listener if you are using jQuery.
This should work for you:
$.(document).ready(function() {
$('.text').click(function() {
$(this).toggle();
});
});
Is very easy. You can use ID or CLASS.
onclick="$('NAME ID or CLASS').toggle(ANIMATION or DURATION);"
<div>
<div class="text" onclick="$('.text2').toggle(400);">Show More</div>
<div class="text2" style="display:none">Show Less</div>
</div>

Categories