jQuery, Hiding Paragraphs - javascript

I'm creating a random html page with internal jQuery, I'm trying to get jQuery to hide two of three paragraphs, and to do this for 5 seconds, but when I load the html file, all paragraphs are immediately visible. Can anyone help?
<html>
<head>
<script src="jquery-1.9.1.js"></script>
</head>
<body>
<script>
var $ = jQuery;
$("p").each(function (idx) {
if(idx >= 1) {
$(this).hide(500);
}
});
</script>
<p>This is the first paragraph</p>
<p>This is the second paragraph</p>
<p>This is the third paragraph</p>
</body>
</html>

You have to wrap your code with $() because the elements aren't loaded yet.
$(function(){
$("p:not(:first-child)").hide(5000);
});
 TRY-A-DEMO
Also I believe 500 is a typo since 5000 is 5 seconds.
As #David Thomas suggested, you can further simplify it into:
$(function(){
$("p:gt(0)").hide(5000); //:gt means "greater than..."
});

Make sure to wait DOM ready event:
$(document).ready(function() {
// your code
});

Related

How to execute a script by call his id

from the html below I would like to execute a script by calling his id. So that when the script id is called the display fonction execute. Any other suggestion will be appreciate as long that the script only execute when the id is called. Thank you
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
//Here is where I would like to execute the script by calling his id.
//Any other suggestion to make it work will be appreciate
});
</script>
<script type="text/javascript" id="execute">
$(document).ready(function(){
display();
});
</script>
<!--------------------- Footer -------------------------------->
<script>
function display(){
$("#show").css("display", "block");
}
</script>
<p id="show" style="display:none">This is a paragraph with little content.</p>
</body>
</html>
That's not how JavaScript works.
Once you include a <script> in DOM, it's executed. However, the script itself can define functions, which could be named and called at a later point (by their name), by any other script or element in the page, as long as they have access to the context in which you defined your function.
Example:
<script>
function myFunction() {
window.alert('I got called!');
}
</script>
<button onclick="myFunction()">Execute myFunction()</button>
So instead of using the id of the script, I'm using the name of the function.
To fully answer your question: running a script by id is not possible because all scripts are executed as soon as they are parsed by the browser (which happens in their chronological order in DOM) and there is no way of re-running them after they have already been executed.
Obviously, one could argue that you could remove the <script> tag altogether, create a new one with the same contents, which is going to be rerun when added to DOM. But, at least in theory, it's not rerunning the same <script>, it's running a different one. Another instance/<script> tag.
Needless to say, nobody does that as it's much more convoluted than to simply define a function and call that function at a later time.
Thank you for your explanation on the DOM. It help me figure out another alternative
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
var result = window.prompt("Would you like the footer to be display?");
if(result == "yes"){
bodyPage1();
}
});
</script>
<script>
function bodyPage1(){
display();
}
</script>
<!--------------------- Footer -------------------------------->
<script>
function display(){
$("#show").css("display", "block");
}
</script>
<p id="show" style="display:none">This is a paragraph with little content.</p>
</body>
</html>

JavaScript- cannot change style when my script in head

I'm trying to get my JavaScript to work when I insert the script into the head or body elements.
Here are my examples:
Firstly I insert it into the body like this example (working):
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
When I move the script into the end of the body (also working):
<html>
<body>
<p id="p2">Hello World!</p>
<p>The paragraph above was changed by a script.</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
But when I move it into the head it stops working:
<html>
<head>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</head>
<body>
<p id="p2">Hello World!</p>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
Use keyword defer for this:
Description of defer:
A script that will not run until after the page has loaded.
<html>
<body>
<p id="p2">Hello World!</p>
<script defer>
document.getElementById("p2").style.color = "blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
you can use window.onload which means that it will invoke only after HTML page is loaded. Here is a quick reference for your study . Thank You!
the problem is your script in head and p2 has not define yet
so you write script in document.ready its work because script run after document has been load
for run jquery code you need to add jquery library for this
link:jquery library
or write code in
window.onload = function() {
document.getElementById("p2").style.color = "blue";
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script>
$(document).ready(function() {
document.getElementById("p2").style.color = "blue";
});
</script>
</head>
<body>
<p id="p2">Hello World!</p>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
it is because you are calling p2 at head and it is not defined at that moment. compiler don't know where is p2 that's why it is showing undefined.
One of the solutions is to do it like below:
window.onload = function () {
document.getElementById("p2").style.color = "blue";
}
The above script will run when the page is loaded completely
"Why it does not work when I insert script in head?"
This is because the script is trying to access a DOM object before it exists. It's one of the main reasons jQuery users tend to use $(document).ready(); wrapped around there functions.
An older practice was to always load your script below the body of your HTML document, however it came with it's own problems.
Using <script defer> /* your code here */ </script> is the generally accepted method if you want your script to only execute after the document is loaded. Alternatively, you can use an external library like jQuery and use:
$(document).ready(function(){
//your code here
});
If you do decide to use jQuery, you could also replace your current script (document.getElementById("p2").style.color = "blue";) with:
$(document).ready(function(){
$('#p2').css({'color':'blue'});
});
This however isn't necessary, just an interesting option to consider
When your script code is in the head tag, it is executed but the DOM element is not ready yet. So, no change occurs. For such cases always use body.onload, because then your script will be executed after the elements in the body is ready.
Bonus: The script will also not work if you place it in the <body> above the <p> tag.

Multiple toggle buttons, 1 jQuery code

Trying to work out if it's possible to have multiple toggle buttons on my page while not having to repeat jQuery .toggleClass code for each button (with different id's)? Maybe use 'this' or some other method?
$(document).ready(function(){
$("button").click(function(){
$("p").toggle('fast');
});
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<button>Toggle</button>
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
<button>Toggle</button>
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
</body>
</html>
Thanks in advance!
You can use event delegation.
For example, if you bind click event to buttons. I think you can use id or data attribute to differentiate which button is triggered. Then you can move forward.
to toggle the next p you need to use .next()
$(document).ready(function(){
$("button").click(function(){
$(this).next('p').fadeToggle('fast');
});
});
to toggle the next p and next next p you need to use .next()
$(document).ready(function(){
$("button").click(function(){
$(this).next('p').fadeToggle('fast');
$(this).next().next().fadeToggle('fast');
});
});
you can select your button ids like
$("#button1, #button2").click();
I don't prefer your html structure .. if you can put each button and its P in one div it will be better to handle
$(function() {
$('#toggle-event1,#toggle-event2,#toggle-event3,#toggle-event4,#toggle-event5').change(function() {
let state1 = $(this).prop('checked');
//alert( "First handler for .toggle() called." );
alert(this.id);})

Detach function in javascript called from Razor

After finding that the hidden attribute only works with html5 and latest browsers I might have found another way to hide content based on conditional statements.
I ran into a problem where the function in javascript does not seem to executed, in short it does not hide the first paragraph.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function DetachEmptyField(pattern) {
$("#pattern").val(pattern);
$(pattern).detach();
}
});
</script>
</head>
<body>
<p id="hideMe">This is a paragraph, 1.</p>
<p>This is another paragraph, 2.</p>
<button>Remove paragraph 1</button>
#* Razor conditional statements to be added later here ... *#
<script type="text/javascript">DetachEmptyField("#hideMe");</script>
</body>
</html>
The DetachEmptyField function is not available in the global scope (it lives inside your ready callback) and therefore your call will not work. If you really want to call it like this
<script type="text/javascript">DetachEmptyField("#hideMe");</script>
you will have to declare it in the global scope (be aware that this is a bad practice)
// global function
function DetachEmptyField(pattern) {
$("#pattern").val(pattern);
$(pattern).detach();
}
$(document).ready(function(){
});
Anyway, if you just need to hide the element you can use css "display: none" or if you can check on the server side whether or not the element should be present on the page you can simply not include that paragraph in the response.
#if ( /*some condition that needs to be true in order to display the <p> */ ) {
#: <p id="hideMe">This is a paragraph, 1.</p>
}

Accessing two different buttons in JQuery

I am new to web development and I am learning JQuery now. I have a doubt here. This is the code from W3Schools.com. I would like to know if I add one more button here, how can I run this JavaScript for the click event of the FIRST button only.
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
<br />
<button>Second Button</button>
</body>
</html>
You can add an ID to the button and put a click event on that id by selecting like this (if button id is 'submitForm') $("#submitForm")
In fact, there are many ways you can select elements with jquery, check this out: http://api.jquery.com/category/selectors/
In your specific example, if you don't want to put ID's on buttons, you could use :first to only access the first one, like this $("button:first")
Change
$("button").click(function(){
$("p").hide();
});
to
$("button").eq(0).click(function(){
$("p").hide();
});
This will only bind to the click event of the first button. See http://api.jquery.com/eq/.
jsFiddle example

Categories