Onclick function based on element id - javascript

I'm working on a site with a visualization of inheritance relation.
I try to link each nodebox with specific URLs. The html of Element looks like this:
<g class="node" id="RootNode" transform="translate(0,453.125)">
I used
$('#RootNode').click(function(){//do something}
and also
document.getElementById("RootNode").onclick(){//do something}
Neither of them can find the element, nor setup the onclick function.
Have I misunderstood anything? Any information will be helpful. Thanks.

Make sure your code is in DOM Ready as pointed by rocket-hazmat
.click()
$('#RootNode').click(function(){
//do something
});
document.getElementById("RootNode").onclick = function(){//do something}
.on()
Use event Delegation/
$(document).on("click", "#RootNode", function(){
//do something
});
Try
Wrap Code in Dom Ready
$(document).ready(function(){
$('#RootNode').click(function(){
//do something
});
});

you can try these:
document.getElementById("RootNode").onclick = function(){/*do something*/};
or
$('#RootNode').click(function(){/*do something*/});
or
$(document).on("click", "#RootNode", function(){/*do something*/});
There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload or DOMReady event, like:
//in Vanilla JavaScript
window.addEventListener("load", function(){
document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
$('#RootNode').click(function(){/*do something*/});
});

$(document).ready(function() {
$("#click").click(function(){
console.log("button clicked");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="click">Click Me</button>

You can try this one:
document.getElementById("RootNode").onclick = function() {
/* do something */
};

Related

jQuery radio button on change does not work

I have seen this question and I have seen this fiddle.
My Fiddle here. It's a simple question. Why doesn't it work?
#html
<input checked="checked" id="article_format_html" name="article[format]" type="radio" value="html">Some meaningful value
<input id="article_format_text" name="article[format]" type="radio" value="text">Another Value
#js
$("input[name='article[format]']:radio").change(alert('hola'));
Edit:
On popular demand I did this:
.change(function(){alert('hola')});
Fiddle.
Result: Doesn't work.
Edit 2: (Why I had the problem)
So, JS-Fiddle wraps your js code in the head of the iframe that is your Result section. For jQuery selectors (or any js that manipulates the DOM) to work properly, it has to be executed *after* the DOM element has been rendered. Hence, wrapping your code on ready and/or just before body closes, is the safest way to ensure that your query selectors don't return undefined.
Use a callback or anonymous function block
You are using jQuery 1.11 (better to use .on syntax)
Demo: http://jsfiddle.net/abhitalks/e5ByP/2/
$("input[name='article[format]']:radio").on("change", function() {
alert('hola');
});
You code is not working because you are not wrapping your jQuery inside document.ready function:
$(document).ready(function()
{
$("input[name='article[format]']:radio").change(function()
{
alert('hola')
});
});
FIDDLE DEMO
The code with .on() should be:
$(document).on('change',"input[name='article[format]']:radio",function(){alert('hola')});
Working fiddle:
http://jsfiddle.net/e5ByP/10/
Wrap that in a anonymous function and DOM ready:
$(function () {
$("input[name='article[format]']:radio").change(function () {
alert('hola')
});
});
Demo:http://jsfiddle.net/e5ByP/6/
That is because you have incorrect change handler syntax. also you need to wrap the code in DOM ready :
$("input[name='article[format]']:radio").change(function(){
alert('hola')
});
Demo
In your code you not wrap handler with .change()
handler is A function to execute each time the event is triggered.
Type: Function( Event eventObject )
Try This :
$("input[name='article[format]']:radio").change(function(){
alert('hola')
});
Working Example
Please use anonymous callback function in change event
$("input[name='article[format]']:radio").change(function(){
alert('hola');
});
Put the code in document ready and try like this. Please see the syntax too
$(function () {
$("input[name='article[format]']:radio").change(function () {
alert('hola')
});
});
put that in side document raedy
like this:
$(document).ready(function () {
$("input[name='article[format]']:radio").change(function(){
alert('hola')
});
});
demo
Use the below code
Always use DOM manipulation and events only after DOM gets fully loaded
$(document).ready(function(){
$("input[name='article[format]']:radio").change(function(){alert('hola')});
});
You forgot the $(document).ready() and also u forgot to write function() in change()
$(document).ready(function(){
$("input[name='article[format]']:radio").change(function(){
alert('hola')
});
});

click event to a JQuery object before adding it to the DOM

Attaching the click event to a JQuery object before adding it to the DOM is done like this I believe.
$('.Button').on('click', '#Your-Selection', function () {
console.log("yeahhhh!!! but this doesn't work for me :(");
});
Is there a way to attach it to a span child of #Your-Selection. This does not work but something like:
$('.Button').on('click', '#Your-Selection span', function () {
console.log("yeahhhh!!! but this doesn't work for me :(");
});
Please use like this
$(document).on('click', '#Your-Selection span', function () {
console.log("yeahhhh!!! this will work for you :)");
});
this will attach click event to the span child of #Your-Selection
I think you are not asking the right question, please
take a look at the jquery on method documentation:http://api.jquery.com/on/
If neither .Button exists (on DOM load) is better to attach it to the body, but if it
exists is better attach to body that the whole document, or the closest tag you have in DOM
You should do something like this:
$("body").on("click", ".Button #Your-Selection span", function(){
//whatever you want
});
As per the jQuery API documentation I have doubts with below solutions. The correct way I think is like as follows:
$('#Your-Selection').on('click','span',function(){
console.log('yeahhhh!!! this will work');
});
so if the button is inside the span you can modify the above code as follow
$('#Your-Selection').on('click','span .Button',function(){
console.log('yeahhhh!!! this will work');
});
So the event only need to be bubble up one level. If you use document or body event need to bubble up so many levels if your HTML structure is complex.

Image not clickable after loaded via AJAX

I have a set of images that are loaded via jQuery AJAX. For some reason, my click handler won't trigger when it is clicked.
JavaScript:
$(document).ready(function()
{
$('img.delete_related_sub').click(function()
{
alert('testing');
});
//I added this part to test, because the above wasn't working...
$(document).click(function(event)
{
alert(event.target.tagName+' '+event.target.className);
});
});
HTML:
<img data-rsid="2" class="delete_related_sub" src="image.png" />
So my 2nd click handler alerts me with "IMG delete_related_sub". But the first one isn't triggered. The is actually in a table that is actually in a pane run by bootstrap tabs, not sure if that'd actually help though.
Try it like this
$(document).on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Just replace document with a static parent of your image.
Use this:
$("body").on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Or, in the success: give this:
$('img.delete_related_sub').click(function() {
alert('testing');
});
Because the line to bind the event runs before the element is added, try using
$(parent).on('click', 'img.delete_related_sub', function() {});
where the parent is a static element that will be there for sure. This works because the event is bound to an element that actually exists, then checks to match your selector. See .on() for more details.
Something like
$(document).on('click', 'img.delete_related_sub', function() {});
would work fine.
$('.delete_related_sub').live("click", function()
{
alert('testing');
});
Use live event to listen clicks

I'm having a jQuery onclick issue

So I'm going to explain this with an example.
I have a "like" button (class: .like) for my feed or stream. When the user clicks it ( using $(".like") ), it ajaxes it's way to refreshless insert the like into the database (using jQuery).
When it's inserted, I change the text to "Unlike" and the class to ".unlike".
However, when a user reclicks it, it just goes through the same function again, instead of going to the $(".unline").click function. Do I have to "update" the script or something?
For example:
$(".like").click(function(){
alert("Like!");
$(this).attr("class", "unlike");
});
$(".unlike").click(function(){
alert("Unlike!");
$(this).attr("class", "like");
});
The problem is that it won't to the unlike function, it will just repeat the like function even though the attribute is changed.
That is because the "unlike" attr. hasn't been added to the dom when the script loaded. Try this:
<body>
<div class="like_it_or_not">
HELLO!
</div>
</body>
And the JS
$("body").on('click','.like_it_or_not', function(){
$(this).toggleClass('like', 'unlike');
if ($(this).hasClass('like')) {
alert('like');
} else if ($(this).hasClass('unlike')) {
alert('unlike');
}
});
If you don’t want to delegate your click event (which is over-engineering IMO), do a check in the handler:
$(".like").click(function(){
alert( $(this).hasClass('unlike') ? 'unlike' : 'like' );
$(this).toggleClass("unlike like");
});
http://jsfiddle.net/NScyM/
It should check for the 'unlike' class each time you click and toggle classes as expected.
The event binding occurs when you assign run the above code. You have to rebind the event every time, or, better yet, use event delegation:
$(document)on("click",".like",function(){
alert("Like!");
$(this).addClass("unlike");
$(this).removeClass("like");
});
$(document)on("click",".unlike",function(){
alert("Unike!");
$(this).addClass("like");
$(this).removeClass("unlike");
});
I think you will have to use live() or on() to make this work:
$(".like").live("click", function() {
$(this).removeClass("like").addClass("unlike");
});
$(".unlike").live("click", function() {
$(this).removeClass("unlike").addClass("like");
});
Try this one
$(".like").click(function(){
alert("Like!");
$(this).removeClass("like");
$(this).attr("class", "unlike");
});
$(".unlike").click(function(){
alert("Unlike!");
$(this).removeClass("unlike");
$(this).attr("class", "like");
});
To keep my code clean on stuff like this, I assign a class that never changes and tie the click event to that. The styling classes simply act as CSS changes. For instance:
<button class="vote like">button text</button>
$('.vote').click(function () {
var alertText = ($(this).hasClass('like')) ? 'Like!' : 'Unlike!';
alert(alertText);
$(this).toggleClass('like').toggleClass('unlike');
});
Try this
$(document).on('click', '.like', function(){
alert("Like!");
$(this).html('Unlike').removeClass("like").addClass("unlike");
});
$(document).on('click', '.unlike', function(){
alert("Unlike!");
$(this).html('Like').removeClass("unlike").addClass("like");
});
DEMO.
The unlike click event handler has not been associated with the new item. If you're going to be changing the class dynamically like that you're going to want to look at the (jQuery on handler)[http://api.jquery.com/on/]
$(document).on('click',".like", function(){
alert("Like!");
$(this).addClass("unlike").removeClass('like');
});
$(document).on('click',".unlike",function(){
alert("Unlike!");
$(this).addClass("like").removeClass('unlike');
});

JavaScript / jQuery problem on Internet Explorer 7

I have a simple HTML page that looks like this:
...<div id="main">
Click here!
</div>...
I have a piece of jQuery JavaScript in the header that looks like this:
<script type="text/javascript">
$(document).ready(function() {
DoHello();
});
function DoHello()
{
$("div#main a").text("Click here!");
$("div#main a").attr("onmouseup", "javascript:alert('Hello!');");
}
</script>
When I click the HTML link in FireFox then I get an alert that says 'Hello!'. Why does this not work in IE7/8?
When I look at the (dynamically) build DOM in IE then I can see the onmouseup is present but it is never called. I have tried replacing onmouseup with onclick - same problem...
You shouldn't be using the JavaScript pseudo protocol for anything.
This should work:
function DoHello()
{
$("div#main a")
.text("Click here!")
.mouseup(function(){
alert('Hello!');
});
}
Don't use expando events, use jQuery!
$("div#main a").mouseup(function(){ alert('Hello!') });
instead of adding the onmouseup event like that why dont you just use the jQuery method like so:
$("div#main a").mouseup(function() {
alert("hello");
});
should work :) for more info check out - http://docs.jquery.com/Events/mouseup
You should use the bind function like this:
function DoHello(){
$("div#main a").bind("mouseup", function(e){
alert("Hello!");
});
}

Categories

Resources