Identical JQuery function is working for one link, not another - javascript

I have the function:
<script type="text/javascript">
$(function() {
$('#subbutton').click(function() {
$('#subbutton').hide();
});
});
</script>
It simply makes this button hide when clicked:
<a id="subbutton" class="button" href="javascript:TINY.box.show({url: 'follow',width:600,height:170,openjs:'initPopupLogin',opacity:30})"><span>Button</span></a>
Now, if i try to use the identical function, but with a link later on the page, it doesnt work (i have erased the original button at this point) Here is the code:
<div id="subbutton">
<span>Button</span>
</div>
I have tried putting the id in the anchor and in the span, nothing seems to be working for this link. Any idea why this isn't working? (I have deleted the original button so that this second button is a unique id on the page)

Try using .on instead to attach your event handler. I am suspecting the button is not in the dom at the time you attach the event handler.
$(document).on('click', '#subbutton', function() {
$(this).hide();
});
EDIT now that i understand the problem. You are better off giving the buttons a class and using a class selector.

.hide doesn't remove the element from the page so your selector will still be matching on the first element. You need to use .remove to remove the first element from the DOM so the second selector can work.
Also, little jQuery optimization. The nested call to $('#subbutton') is not needed. At best, it is harder to maintain, at worst, it could cause performance issues if you put this in a large loop. This is better.
$(function() {
$('#subbutton').click(function() {
$(this).remove();
});
});

You are missing a " after this:
<a id="subbutton" class="button
and Id has to be unique. Then it should work.

Don't reuse ids, they must be unique. pass the id to the function

Change your javascript to:
$(function() {
$('#subbutton').live("click",function() {
$(this).hide();
});
});​
http://jsfiddle.net/W2agx/
also don't reuse id's. use a class for multiple DOM elements that you want to be able to select together.

Related

.click() not working on a specific index

I'm creating a dynamic menu where I can add and remove a new form.
<input type="button" value="generate form" id="test"/>
<div id="form1"></div>
<script>
$(document).ready(function() {
$("#test").click(function() {
$("#form1").append("<select id='score-attempt'><option value='penalty'>penalty</option></select><input type='button' value='remove' id='remove'/><br>");
});
$("#form1 #remove").click(function() {
alert($(this).index());
});
});
The problem is that clicking on remove never triggers the alert box.
Thanks
The problem is that the element is added later and doesn't exist when the dom is loaded. Therefore the click event has to be delegated from an already existing element, e.g. like this:
$(document).on("click", "#remove", function(){
alert($(this).index() );
});
Instead of $(document) every other static parent element can be used for event delegation, just as example.
Update for the comments: as mentioned, $(document) only as example. I'd also prefer to use $("#form1") here like mithunsatheesh suggested.
And for reference: https://api.jquery.com/on/#on-events-selector-data-handler, section "Direct and delegated events":
"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."
Update for the correct index: you'll get the correct index using e.g.
$("#form1").on("click", ".remove", function(){
alert($(".remove").index($(this)));
});
with the adjustment to use remove as class instead of id for the remove-button. IDs have to be unique, so classes are a better solution. index() starts counting with 0, so you'll get 0 for the first one.
As working example: Fiddle
You need to add an event handler on your #form1 input with #remove.
Look here, here and here.
Here is the working jsfiddle for you.

How to perform: onClick Javascript, hide a div with transition effect

This is a question that is related to a previous question of another member which can be found here.
This is the Javascript function to hide a div (which is an answer to the other member's question):
function hide(obj) {
var el = document.getElementById(obj);
el.style.display = 'none';
}
The HTML is:
<div id='hideme'>
Warning: These are new products
<a href='#' class='close_notification' title='Click to Close'>
<img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="hide('hideme')" />
</a>
</div>
My followup question to this is: how can I add a cool effect of transition? The result will be the div 'hideme' would close slowly. Is there a work around for this?
Thanks so much everyone! It would be highly appreciated!
Note: I'm a noob with Javascript. 0-0
$("#"+el).fadeOut(500);//el must be the id of the element
If you're using jQuery
function hide() {
$(this).parent().fadeOut();
}
As this is triggered by an event the 'this' variable will be set to the element from which it came, as you want the parent element to vanish when it's clicked this will do the trick
EDIT: For this to work you may have to play with your HTML and how many $(this).parent().parent()... you need but this would be the best way to go about it, then you don't need to pass the ID around
EDIT 2: So .parent() selects the element containing the selected element, so in this case $(this) refers to the button that was clicked as that's where the click event came from.
So $(this).parent() refers to the container element, in this case the a element and therefore the $(this).parent().parent() refers to the div element which you want to hide.
So you could give the image a class of 'closable' then do the following
$('.closable').click(function() {
$(this).parent().parent().fadeOut();
}
This means whenever you click something with the class closable it will go up the DOM tree two elements to (with .parent().parent()) and then fade it out.
This will allow you to remove the on click event from the image, you just need to put the handler above in the jQuery document.ready function which looks like:
$(document).ready(function() {
//Click function here
});
A popular choice for this would be JQuery UI's effect method.
With this, you can write some very simple Javascript to hide your div in a stylish manner, for example:
function hide(obj) {
$(obj).effect("scale");
}
EDIT:
Here's an example jsFiddle
Use jQuery to do transition effects:
$(function(){
$("a.close_notification").click(function(e){
e.preventDefault();
// stop other animations and hide, 500 milliseconds
// you can use the function fadeOut for that too
$("#hideme").stop().hide(500);
});
});

How to get the id of an element ON PAGE LOAD using jQuery

I simply know how to get the id of a clicked element it's like this:
$("button").click(function(){
console.log($(this).attr("id"));
}
but what can I do for getting the id on web page load? Look at this..
$("button").ready(function(){
console.log($(this).attr("id"));
}
it returns the whole document object and this one ..
$("button").load(function(){
console.log($(this).attr("id"));
}
simply does nothing.
I want to dynamically change the styles of all buttons on load.
The main project is more complicated, and I don't want to use js core to do it, I want the simplicity of jQuery selector, but equivalent js approaches are appreciated.
i want to dynamically change the styles of all buttons on load.
If that is the case you can simply apply the css to the button selector on load, without needing to get the id of each button.
$(function() {
$("button").css("background-color", "#C00");
});
Or better yet, put the css styling into a class and just apply a class to all the buttons:
$(function() {
$("button").addClass("red-bg");
});
If you did want to get the id of each button on load, you'd need to use an array to cater for the fact there may be more than one button:
var buttonIds = $("button").map(function() {
return this.id;
}).get();
However, this is a rather pointless method as you can just use each() to iterate over the button selector anyway to get access to each indiviual button element.
you can get the all button elements in jquery and then loop on each button element to change their style -:
$(function()
{
var allButtons = $('button');
$.each(allButtons,function(index,element)
{
$(element).css('width','100px');
});
});
I think you're looking for this:
$(document).ready(function () {
$(":button").each(function () {
console.log($(this).attr("id"));
})
});

jQuery Class selector not working

I'm struggling to make an alert come up when an anchor tag with a specific class is clicked inside of a div.
My html section in question looks like this...
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
The jQuery section is as follows..
$('.bar').click(function()
{
alert("CLICKED");
});
My problem is that I cannot get this alert to come up, I think that I'm properly selecting the class "next", but it won't pick it up for some reason. I've also tried almost everything on this page but nothing is working. If I don't try to specify the anchor tag i.e. $('#foo').click(function()... then it works, but there will be multiple anchor tags within this div, so simply having the alert executed when the div is clicked won't work for what I need. The website this is on is a search engine using ajax to send information to do_search.php. Within the do_search.php I make pagination decisions based on how many results are found, and if applicable, a next, previous, last, and first link may be made and echoed.
EDIT: I just figured it out, it was my placement of the .next function, since it wasn't created on the initial document load but instead after a result had been returned, I moved the .next function to the success part of the ajax function since that is where the buttons will be created if they need to be, now it works.
Try using the live() command:
$(".bar").live("click", function(){ alert(); });
Because you load your button via AJAX, the click event isn't binded to it. If you use the live() command, it will automatically bind events to all elements created after the page has loaded.
More details, here
.live is now deprecated and is the selected answer for this. The answer is in the comments in the selected answer above. Here is the solution that resolved it for me:
$(document).on('click','.bar', function() { alert(); });
Thanks to #Blazemonger for the fix.
You surely missed $(document).ready(). Your code should be:
$(document).ready(function(){
$('.bar').click(function()
{
alert("CLICKED");
});
});
Hope this helps. Cheers
Make sure you have included JQuery Library properly.
Make sure your script has written between $(document).ready() in short $(function(){ });
Demo : http://jsfiddle.net/W9PXG/1/
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
$(function(){
$('a.bar').click(function()
{
alert("CLICKED");
});
});

jQuery addClass onClick

The setting is easy; I want to be able to add a class to (in this case) a button when onClick-event is fired. My problem is that I haven't found a way to pass the button itself as the parameter to the function. I'd like to do something like:
<asp:Button ID="Button" runat="server" onclick="addClassByClick(this)"/>
And then a javaScript function something like this:
function addClassByClick(button){
button.addClass("active")
}
I know I've got a lot of errors here, but that's why I'm posting. I've tried different scenarios with jQuery and without jQuery but I always end up with a broken solution (clicks suddenly stop coming through, class not added etc etc) so I decided to ask the pro's.
Any suggestion to what I can try? Thanks for reading editand all the help!
It needs to be a jQuery element to use .addClass(), so it needs to be wrapped in $() like this:
function addClassByClick(button){
$(button).addClass("active")
}
A better overall solution would be unobtrusive script, for example:
<asp:Button ID="Button" runat="server" class="clickable"/>
Then in jquery:
$(function() { //run when the DOM is ready
$(".clickable").click(function() { //use a class, since your ID gets mangled
$(this).addClass("active"); //add the class to the clicked element
});
});
Using jQuery:
$('#Button').click(function(){
$(this).addClass("active");
});
This way, you don't have to pollute your HTML markup with onclick handlers.
$(document).ready(function() {
$('#Button').click(function() {
$(this).addClass('active');
});
});
should do the trick.
unless you're loading the button with ajax.
In which case you could do:
$('#Button').live('click', function() {...
Also remember not to use the same id more than once in your html code.
$('#button').click(function(){
$(this).addClass('active');
});
Try to make your css more specific so that the new (green) style is more specific than the previous one, so that it worked for me!
For example, you might use in css:
button:active {/*your style here*/}
Instead of (probably not working):
.active {/*style*/} (.active is not a pseudo-class)
Hope it helps!

Categories

Resources