I have a jQuery requirement like:
I have an Image. If I click it once its size will get reduced. If I again click it it will again resize.
Do we have any functionality to do it easily in jQuery? Or do I have to set a flag and then work on mouseclick? Something like
$("#img1").click(function() {
$("#img1").addClass("img1");
});
Don't use toggle, when there is toggleClass function :)
$("#img1").click(function() {
$("#img1").toggleClass("img1");
});
jQuery toggle function might help.
In short=>
CSS:
.small{width: 10px;}
Javascript:
var makeSmall = function(){
$(this).addClass("small");
};
var makeNormal = function () {
$(this).removeClass("small");
};
$("#id").toggle(makeSmall, makeNormal);
Also - you might want to change CSS directly through jQuery:
var makeSmall = function(){
$(this).css({'width' : '10px'});
}
P.s. Thinker's approach with toggleClass is cleaner.
Related
I need to trigger an event when i add a specific class on button, but I have no idea how to make it listen to the class adding event.
I have something like this:
<script type="text/javascript">
$(document).ready(function() {
$(id_element).addClass("active");
//this function will fire on add "active" class to "id_button" element
function fireOnActiveClass() {
//do something
}
}
</script>
I can't touch code $(id_element).addClass("active");, for more reasons.
Currently I use jQuery 1.7.2
Could you please tell me how or which I need to know?
You are modifying the class of the control in your code. So why not simply call the click of the button when you change the class ?
$(id_element).addClass("active");
$(id_button).click();
$(id_button).click(function () {
if ($(this).hasClass) {
//do something
}
});
There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:
$(document).ready(function() {
$(id_element).addClass("active").trigger('classChange');
$(id_element).on('classChange', function() {
// do stuff
});
});
One other way would be to call a function right after adding the class like:
$.fn.classAdded = function() {
var $button = $(this);
if($button.hasClass('id_button')) {
// ...
}
return $button;
}
$(id_element).addClass("active").classAdded();
I have found solution using this jQuery Plugin: http://meetselva.github.io/attrchange/
Could this jQuery plugin be any help?
https://github.com/tormjens/jquery-dom-router
You can change the default element using
$.DOMRouter.defaults.element = '#element';
before initalizing the plugin.
I have written a short plugin for jQuery which will change the styles of the browser's in-built checkbox, so that it better fits with the theme.
Here is the plugin code:
(function ($) {
$.fn.checkbox = function()
{
var uiBox = $('<span class="ui-checkbox" />'),
that = this;
uiBox.data('checkbox', this).insertAfter(this);
this.hide();
if(this.is(':disabled')) { uiBox.addClass('disabled'); }
if(this.is(':checked')) { uiBox.addClass('checked'); }
if(!uiBox.hasClass('disabled'))
{
uiBox.on('click', function() {
var checkbox = $(this).data('checkbox');
if(checkbox.is(':checked'))
{
uiBox.removeClass('checked');
checkbox.attr('checked', false);
}
else
{
uiBox.addClass('checked');
checkbox.attr('checked', 'checked');
}
});
}
};
} (jQuery));
This code is then in turn called through the DOMReady handler using:
$('input[type="checkbox"].ui').checkbox();
Everything works the first three times the 'checkbox' is clicked, but thereafter for some reason the code no longer executes the addition / removal of the necessary classes, and the original checkbox is never updated. Can anyone shed any light on the situation, and explain why this is happening?
jsFiddle Demo
It's because you're using attr() and not prop(), changing just the attribute and not the underlying property, change it to
checkbox.prop('checked', true);
FIDDLE
Use .prop() instead of .attr()
checkbox.prop('checked', 'checked');
Demo
Use this following code, I have tried it in your fiddle example it is working there,
checkbox.prop('checked', true);
Hope this Helps!
My script doesn't seem to be working correctly, what I'm trying to get is pretty self explanatory. I have tried several diffrent ways to make this work, searched around and tried to solve it.
I also tried to check the chrome log via console.log() but it didn't run the code through.
So if you know the solution to make it work I would appreciate the answer on how you solved it and what was wrong in the code.
NEW: The fiddle below includes the HTML.
jQuery(document).ready(function($){
$('#cart_review .quantity option :selected').change(function (event) {
$quan = $(this);
console.log($quan.parent().next()[0]);
$quan.parent().next().find('.price').text(function () {
return $quan.val() * parseInt($(this).attr('data-val'), 10) + ' kr';
});
var total = 0;
$('#cart_review .price').each(function(k, v){
total += parseFloat($(v).text(), 10);
});
$('#total').text(total + ' kr')
});
});
Check out this jfFiddle
Option does not have change event, select does. You need to Change the handler to:
$('#cart_review .quantity').change(function (event) {
//rest code
});
jfFiddle
use this
$('#cart_review .quantity').change(function (event) {
// your logic here
}
instead of
$('#cart_review .quantity option').change(function (event) {}
working fiddle
Hope this helps...
http://jsfiddle.net/uQ2F8/3/
$(function(){
$('select.quantity').change(function (event) {
Hey I just changed your selector, I think this is what you're trying to accomplish. I did it with the first one.
Maybe someone see and can answer where is a problem why on IE8 not working alert # first line 'lov_Dg2Id_D_1' but on next 'lov_Dg2Id_D_2' all is ok.
var SecondDiagnosis=$( "span[id^='lov_Dg2Id_D_']" );
var SpanBlock2=SecondDiagnosis.find('a');
var eventH2=SpanBlock2.attr( "onclick" );
//SpanBlock2.attr("onclick", "DgIdOnClick(document.getElementById('MovementNumber_D_'+parentElement.getAttribute('id').substring(12)).id,2);"+eventH2);
SpanBlock2.attr("onclick", "alert('HI!');"+eventH2);
Mabe are some other ways how can add a onclick event ?
Thanks Helpfull and Correct Answers guiranteed ;)
Learn about the library you are using.
You do not use attr to set events! jQuery has methods like on() or click() for that.
SpanBlock2.on("click", function() { alert('HI!'); });
You will not need to copy/call the original event, it will still be there.
If you want to change the order, you will need to bind the events
$("button").each(
function() {
var btn = $(this);
var oldClick = btn[0].onclick;
btn.on("click", function(){ alert("a"); });
if(oldClick) {
btn[0].onclick = null;
btn.on("click", oldClick);
}
}
);
http://jsfiddle.net/7K9pU/
change this:
SpanBlock2.attr("onclick", "alert('HI!');"+eventH2);
to this:
var SecondDiagnosis=$( "span[id^='lov_Dg2Id_D_']" );
var SpanBlock2=SecondDiagnosis.find('a');
SpanBlock2.on("click", function(){
// all your stuff you want on click of it.
});
$(textBox).focus( function() {
$(spans).css({"background-position": "0 100%"});
});
$(textBox).blur( function() {
$(spans).css({"background-position": "0 0"});
});
This is already short but it's either I am just too paranoid, or we could code this shorter by
$(textBox).bind('focus blur', function() { *do toggle here* });
or something else.
Any help would be greatly appreciated. =)
Try this:
$( textBox ).focus( function(){...} ).blur( function() {...} );
And yes, you can also use the bind() function as you specified.
I find my version more readable.
Good luck!
You can try this as well:
$(textBox).bind('focus blur', function(e) {
var bg = (e.type=='blur') ? '0 0' : '0 100%';
$(spans).css({"background-position": bg});
});
I think there's a line between optimization and code clarity. Without any further evidence, I don't believe you'll see any major improvements as far as optimizations go.
Keeping these two separate allows for a very quick and easy scan... No logic to go through. Its just "When this happens, then do this". Simple and you're probably losing, if anything, very little.
Edit:
If like you mentioned in a comment you want to toggle the class, you could
$(textBox).bind('focus blur', function() {
var currentClass = $(this).attr('class');
var newClass = currentClass == 'gotFocus' ? 'noFocus' : 'gotFocus';
$(this).removeClass(currentClass).addClass(newClass); });
If you want to use the same function for both the events, you need to use a way of changing the effect that can be used to turn it both ways. Something like:
$(textBox).bind('focus blur', function() { $(spans).toggleClass('over'); });
If there are a lot of elements that you want to change the effect on, you should consider using the cascading effect of CSS instead of letting jQuery change the class for all the elements, i.e. changing the class for a single parent element, and have a style that targets all the child elements that you want to affect:
#container span { background-position: 0 0; }
#container.over span { background-position: 0 100%; }
Changing the class of the parent will change the style of all affected children:
$(textBox).bind('focus blur', function() { $('#container').toggleClass('over'); });
$("#test").bind("focus blur", function (e) {
$(spans).css({"background-position": e.type === "focus" ? "0 100%" : "0 0"});
});