I have a small problem with the #Html.ActionLink tag. I want to change the background when clicking on it. But it doesn't work.
<ul>
<li>#Html.ActionLink("View Profile", "Profile", "User", null, new { id = "profile" })</li>
</ul>
and the jQuery code:
$("#profile").click(function () {
document.getElementById("profile").style.background = "linear-gradient(#00ff66, #00ff99, #00ff66)";
});
But I have tried on w3schools, it already worked:
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<a id="profile" href"">View profile</a>
<script>
$("#profile").click(function() {
document.getElementById("profile").style.background = "linear-gradient(#00ff66, #00ff99, #00ff66)";
});
</script>
</body>
</html>
Can you help me?
p/s: Here is my sub-question:
Can you tell me what is the different between:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<a id="profile" href"">View profile</a>
<script>
$("#profile").click(function() {
document.getElementById("profile").style.background = "linear-gradient(#00ff66, #00ff99, #00ff66)";
});
</script>
and
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$("#profile").click(function() {
document.getElementById("profile").style.background = "linear-gradient(#00ff66, #00ff99, #00ff66)";
});
</script>
<a id="profile" href"">View profile</a>
If I change the position of line <a id="profile" href"">View profile</a> to the end, the code won't work.
Why?
Answer to the main question
It is because your code is running when your page elements are not loaded. So please put script to the bottom or try the following script:
$(function () { //Since it's short and you are using jQuery. You may also use $(document).ready(function(){
$("#profile").click(function () {
document.getElementById("profile").style.background = "linear-gradient(#00ff66, #00ff99, #00ff66)";
});
});
Though you may use the above code and it works, I would recommend you to put the <script> tag always at the bottom of the page to speed up the page load time.
Anyway you can do any of these.
Answer to your sub-question:
It's because when javascript(Jquery) searches for the dom with the id you specified, if it is not loaded it gives out an error and prevents execution.
Hope it solves both of your questions.
Please accept if it is the best answer.
Keep Asking Keep Learning.
Thanks...
I think your problem is because the DOM elements are not fully loaded when the script is starting execution. You could solve the problem if wrap the script like this:
$(document).ready(function(){
$("#profile").click(function () {
document.getElementById("profile").style.background = "linear-gradient(#00ff66, #00ff99, #00ff66)";
});
});
Whenever the script executes it is looking for a dom with id = "profile" and since it hasn't loaded on the page yet, the event will not get bound.
you can fix this by wrapping your code in document ready event:
$(document).ready(function(){
//add event here
});
or in the jquery shorthand notation:
$(function(){
//add event here
});
Any code inside here will fire once your html has loaded.
Another fix to this is to place the event on the document itself and use the 'on' method to specify you are looking for #profile:
$(document).on('click', '#profile', function(){
//do stuff
});
Related
I have a header which I use in several pages, so I would like to use jquery to import it into each page so that I don't have to make any changes several times, using this code:
$(document).ready(function() {
$('#header').load("header.html");
});
The header loads fine, but the problem is that I have a button within that header which I have assigned to a variable:
var headerButton = document.querySelector('.header__header-button')
And I have added an event listener to this button in order to execute some code when it's pressed:
headerButton.addEventListener('click', function () {
The problem is that I'm getting an error in the javascript console:
TypeError: headerButton is null page.js:17:1
The problem seems to be that the variable is being assigned the value before the Html has loaded, although I am not sure.
There is nothing wrong with the variable or the EventListener, it all works when the header is within the main file. So, what can I do to solve this?
.. Or, maybe there is a better way to import Html that I am unaware of?
You should use $(document).ready() inside of header.html as well to make sure your DOM is available before you try to manipulate elements with JavaScript.
Here's an example of the page you're trying to load header.html into:
<!-- index.html -->
<html lang="en">
<head><!-- ... --></head>
<body>
<div id="header"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#header").load("header.html");
});
</script>
</body>
</html>
Then, inside of your header.html, do the following:
<!-- header.html -->
<header>
<p>This is a header.</p>
<button id="button" type="button" className="header">
Header button - click me!
</button>
</header>
<script>
$(document).ready(function() {
var btn = document.getElementById("button");
btn.addEventListener("click", function() {
alert("button was clicked");
});
});
</script>
Here's a working example if you'd like to see a demo:
CodeSandbox
You can try using the callback function.
$(document).ready(function() {
$('#header').load("header.html", () => {
var headerButton = document.querySelector('.header__header-button');
headerButton.addEventListener('click', function () {});
});
});
I'm new to JavaScript and I'm sure that this is a very trivial fix.
I'm dynamically changing a div content based on which button is clicked. This example works in JSFiddle but however when I put it on my PC it simply loads the entire webpage even when I wrap the JS with $(window).load(function(){ ... })
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src= "http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<ul class="menu">
<li>About</li>
<li>Contact</li>
<li>Misc</li>
</ul>
<div id="about" class="menu-content">About</div>
<div id="contact" class="menu-content">Contact</div>
<div id="misc" class="menu-content">Misc</div>
</body>
</html>
My JS (script.js):
$(window).load(function(){
var $content = $('.menu-content');
function showContent(type) {
$('div', $content).hide();
$('div[data-menu-content='+type+']').show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
});
$(window).load(function(){ ... })
replace by :
$(document).ready(function(){ ... })
Replace your (window).load to (document).ready
load is called when all assets are done loading, including images. ready is fired when the DOM is ready for interaction.
load()
The load event fires at the end of the
document loading process. At this
point, all of the objects in the
document are in the DOM, and all the
images and sub-frames have finished
loading.
ready()
While JavaScript provides the load
event for executing code when a page
is rendered, this event does not get
triggered until all assets such as
images have been completely received.
In most cases, the script can be run
as soon as the DOM hierarchy has been
fully constructed. The handler passed
to .ready() is guaranteed to be
executed after the DOM is ready, so
this is usually the best place to
attach all other event handlers and
run other jQuery code. When using
scripts that rely on the value of CSS
style properties, it's important to
reference external stylesheets or
embed style elements before
referencing the scripts.
try this
$(document).ready(function(){
var $content = $('.menu-content');
function showContent(type) {
$('div', $content).hide();
$('div[data-menu-content='+type+']').show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
});
You can try below solution :
function showContent(type) {
$($content).hide();
$('#'+type).show();
}
When i ran your snippet in my PC, I found out that Jquery was not able to find div, based on the selectors you have specified at the time of loading.
Code:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
</script>
The above code doesn't work. When I click on #clicker, it doesn't alert and and it doesn't hide. I checked the console and I get no errors. I also checked to see if JQuery was loading and indeed it is. So not sure what the issue is. I also did a document ready function with an alert and that worked so not sure what I am doing wrong. Please help. Thanks!
You are supposed to add the javascript code in a $(document).ready(function() {}); block.
i.e.
$(document).ready(function() {
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
});
As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"
I found the best solution for this problem by using ON with $(document).
$(document).on('click', '#yourid', function() { alert("hello"); });
for id start with see below:
$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });
finally after 1 week I not need to add onclick triger.
I hope this will help many people
Your code may work without document.ready() just be sure that your script is after the #clicker. Checkout this demo: http://jsbin.com/aPAsaZo/1/
The idea in the ready concept. If you sure that your script is the latest thing in your page or it is after the affected element, it will work.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<a href="#" id="clicker" value="Click Me!" >Click Me</a>
<script type="text/javascript">
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
</script>
</body>
</html>
Notice:
In the jsbin demo replace http with https there in the code, or use this variant Demo
Try adding $(document).ready(function(){ to the beginning of your script, and then });. Also, does the div have the id in it properly, i.e., as an id, not a class, etc.?
You have to wrap your Javascript-Code with $(document).ready(function(){});Look this JSfiddle.
JS Code:
$(document).ready(function() {
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
});
Be sure there is nothing on your button (such a div or a trasparent img) that keeps from clicking the button.
It sounds stupid, but sometimes we think that jQuery is not working and all that stuffs and the problem is on the positioning of DOM elements.
You can use $(function(){ // code }); which is executed when the document is ready to execute the code inside that block.
$(function(){
$('#clicker').click(function(){
alert('hey');
$('.hide_div').hide();
});
});
Just a quick check, if you are using client-side templating engine such as handlebars, your js will load after document.ready, hence there will be no element to bind the event to, therefore either use onclick handler or use it on the body and check for current target
Proper Browser Reload
Just a quick check as well if you keep your js files separately: make sure to reload your resources properly. Browsers will usually cache files, so just assure that i.e. a former typo is corrected in your loaded resources.
See this answer for permanent cache disabling in Chrome/Chromium. Otherwise you can generally force a full reload with Ctrl+F5 or Shift+F5 as mentioned in this answer.
For some reason my jQuery script just doesn't want to work, and it's really really simple, I've taken everything away except the actual jquery script, it's really annoying please help.
Thank you!
<!doctype html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$("#click").click(function () {
alert("works!");
});
</script>
</head>
<body>
Button
</body>
</html>
P.S. jQuery JS file is valid.
Change your code to this. It ensures that the JavaScript is executed once all your HTML elements have been loaded to the page:
$(document).ready(function () {
$("#click").click(function() {
alert("works!");
});
});
However, you should move your script tags to the bottom of the page, to ensure that they do not block. This will also mean you don't actually need the $(document).ready callback.
You need to wrap your code within
$(function(){
// your code here which relies on DOM elements
});
Otherwise you DOM has not been loaded and events will not be bound to elements.
Wrap your functions into the $(document).ready()
$(document).ready(function(){
$("#click").click(function() {
alert("works!");
});
});
Add your code inside document.ready like this
$(document).ready(function () {
$("#click").click(function () {
alert("works!");
});
});
or add your code at the end of the document like this
<body>
Button
// Other elements...
<script type="text/javascript">
$("#click").click(function () {
alert("works!");
});
</script>
</body>
$(document).ready(function(e) {
//TO DO your code goes here
});
Just change your script tag to the "/body" tag.
That will let the browser create the DOM and read script's one by one!
Cheers!
Try this:
$("#click").live("click",function() {
alert("works!");
});
Im trying to show/hide a div using jquery when a link gets clicked. I put this in my head section:
<script type="text/javascript">
$("#attach_box").click(function {
$("#sec_box").show()
});
</script>
I have a link that looks like this:
+ Add a Postal Address (If Different)
And a div that looks like this:
<div id="sec_box" style="display: none;">
Hello world!!
</div>
This doesn't work and I can't figure out why. Any ideas?
You need to attach the click handler in the document.ready in order to make sure that the DOM has been loaded by the browser and all the elements are available:
<script type="text/javascript">
$(function() {
$('#attach_box').click(function() {
$('#sec_box').show();
return false;
});
});
</script>
Also you forgot to put parenthesis () next to the anonymous function in the click handler.
Chances are the DOM isnt fully loaded yet.
<script type="text/javascript">
$(document).ready(function()
{
$("#attach_box").click(function() {
$("#sec_box").show()
});
});
</script>
put that in your head and put your initialization code in there.