Does anyone know of a way of detecting which one out of a series of image input buttons has been clicked on, and execute some javascript accordingly?
for example if an 'about' button is clicked, the 'about' header on the page would turn blue.
I can do this individually but is there a loop or something to slim it down? Thanks in advance!
If your buttons share a class you can use document.querySelectorAll to select all buttons and Array.prototype.forEach.call for the iteration:
<button class="about-button" id="a">a</button>
<button class="about-button" id="b">b</button>
<button class="about-button" id="c">c</button>
<script>
[].forEach.call(document.querySelectorAll('.about-button'), function(el) {
el.addEventListener('click', imageButtonClickHandler);
});
function imageButtonClickHandler() {
alert('button clicked: ' + this.id);
}
</script>
If you are using jQuery you can use the .on method:
$("#about").on("click", function(event){
$(this).css("background-color", "blue"); // Or RGB color, just like in the CSS
});
Source: http://api.jquery.com/on/ and http://api.jquery.com/css/
The question is not fully clear, but I'll try to answer it based on some assumptions.
If you are creating the image buttons dynamically, then I would attach one onclick event handler to all the images buttons being added, and pass 'this' as the parameter to the handler. That way the click handler can look at the DOM element passed in.
<a onclick="imageClicked(this)"><img src="about.jpg" /></a>
If the elements are declared on the page, and not added dynamically, I would bind the click event for each image button if they are not that many (as #Joshua Brodie has pointed out). If there are a lot of them, I would have one click handler and have data specific to the image button in a "data" attribute.
<a class="imgbtn" data-buttonname="about"><img src="about.jpg" /></a>
$('.imagebtn').bind('click', function () {
console.log($(this).data('buttonname')); // about
});
Related
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);
});
});
Trying to figure out proper way to make a click event not fire on the icon of a disabled link. The problem is when you click the Icon, it triggers the click event. I need the selector to include child objects(I think) so that clicking them triggers the event whenever the link is enabled, but it needs to exclude the children when the parent is disabled.
Links get disabled attribute set dynamically AFTER page load. That's why I'm using .on
Demo here:(New link, forgot to set link to disabled)
http://jsfiddle.net/f5Ytj/9/
<div class="container">
<div class="hero-unit">
<h1>Bootstrap jsFiddle Skeleton</h1>
<p>Fork this fiddle to test your Bootstrap stuff.</p>
<p>
<a class="btn" disabled>
<i class="icon-file"></i>
Test
</a>
</p>
</div>
</diV>
$('.btn').on('click', ':not([disabled])', function () { alert("test"); });
Update:
I feel like I'm not using .on right, because it doesn't take the $('.btn') into account, only searching child events. So I find myself doing things like $('someParentElement').on or $('body').on, one being more difficult to maintain because it assumes the elements appear in a certain context(someone moves the link and now the javascript breaks) and the second method I think is inefficient.
Here is a second example that works properly in both enabled/disabled scenarios, but I feel like having to first select the parent element is really bad, because the event will break if someone rearranges the page layout:
http://jsfiddle.net/f5Ytj/32/
Don't use event delegation if you only want to listen for clicks on the .btn element itself:
$('.btn').on('click', function() {
if (!this.hasAttribute("disabled"))
alert("test");
});
If you'd use event delegation, the button would need to be the matching element:
$(someParent).on('click', '.btn:not([disabled])', function(e) {
alert('test!!');
});
Demo
Or use a true button, which can really be disabled:
<button class="btn" [disabled]><span class="file-icon" /> Test</button>
Demo, disabled.
Here, no click event will fire at all when disabled, because it's a proper form element instead of a simple anchor. Just use
$('.btn').on('click', function() {
if (!this.disabled) // check actually not needed
this.diabled = true;
var that = this;
// async action:
setTimeout(function() {
that.disabled = false;
}, 1000);
});
.on('click', ':not([disabled])'
^ This means that, since the icon is a child of the button ".btn", and it is not disabled, the function will execute.
Either disable the icon, also, or apply the event listener only to the <a> tag that is your button, or use e.stopPropagation();
I would suggest using e.stopPropagation();, this should prevent the icon from responding to the click.
That doesn't seem to work for me ^
Disabling the icon, however, does.
I would prefer to add the event using delegation here as you are trying to base the event based on the attributes of the element.
You can add a check condition to see if you want to run the code or not.
$('.container').on('click', '.btn', function() {
if( $(this).attr('disabled') !== 'disabled'){
alert('test!!');
}
});
Check Fiddle
You're not using the selector properly.
$('.btn').not('[disabled]').on('click', function () {
alert("test");
});
See it live here.
Edit:
$('.container').on('click', '.btn:not([disabled])', function () {
alert("test");
});
I think what you need is:
e.stopPropagation();
See: http://api.jquery.com/event.stopPropagation/
Basically something like the following should work
$('.icon-file').on('click', function(event){event.stopPropagation();});
You may want to add some logic to only stop bubbling the event when the button ist disabled.
Update:
not sure, but this selector should work:
$('.btn:disabled .icon-file')
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.
The code is:
Done
I want this part becomes unclickable once if it is clicked, how to achieve this using Jquery or Javascript?
Use the .one() method which does exactly that ..
$(document).ready(function(){
$('#anch1').one('click', function() {
Record(/* your parameter */);
});
});
Provide the anchor tag an id and remove the onclick handler from the HTML markup.
<a id="anch1" href="#" style="color:black">Done</a>
$(function(){
$("#anch1").bind("click",function(){
// do your action here
$(this).unbind("click"); //unbinds the click event
});
});
How do I perform a jQuery 'slidetoggle' effect using a hyperlink, instead of an input button, as the action item?
At the jQuery reference page
It only gives an example of using a form input button.
I would like to have instead of a button, a hyperlink to be the toggle clickable action.
$("#anch").click(function () {
$("#para1").slideToggle("slow");
});
<a id='anch'>Toggle</a>
<p id='para1'>
This is the paragraph to end all paragraphs. You
should feel <em>lucky</em> to have seen such a paragraph in
your life. Congratulations!
</p>
If you have a link like so:
<a id="toggleLink" href="#">CLICK ME!</a>
Just use the following function to slideToggle your div
$("#toggleLink").click(function () {
$("#myDiv").slideToggle("slow");
});
In addition to the other answers, if your hyperlink has an href attribute (which it should, so it will be displayed as a link), you may want to neutralize it by returning false on your event handler (if you don't, the page will scroll up when you click on the link):
$('a').click(function(){
$('p').slideToggle();
return false;
});
Other than that, there shouldn't be any difference between a button and an hyperlink. While you're reading the documentation, you'd be wise to start with jQuery's Selectors.