jquery swap image on element click not functioning - javascript

I am trying to swap an image on click with jquery. I have got it to work with the click being bound to the image class. However, if I try and wrap the function and bind the event to a button or anchor, it will not swap the images. Here is the jquery:
<script type="text/javascript">
jQuery(document).ready(function( $ ) {
$(".test_toggle").click(function(){
$(this).find(".img-swap").live('click', function() {
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});
});
</script>
This worked:
jQuery(document).ready(function( $ ) {
$(".img-swap").live('click', function() {
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});
Any help is greatly appreciated.

I don't think there's any need to delegate the event listeners so I've removed them. Simply add the click event to the image and then you can manually 'trigger' a click on it when the .test-toggle is clicked. E.G:
$(function() {
//add on click event
$(".img-swap").on('click', function() {
if (this.src.indexOf("_off")>0) {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
});
//add remote trigger
$(".test_toggle").on('click', function(){
$(".img-swap").trigger("click");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="img-swap" src="https://placehold.it/300?text=_off" />
<button class="test_toggle">test toggle</button>

Thats because unlike like img.
a or button doesn't have a src attribute.
So when you bind the event to a button or anchor, this.src in your second instance of the code will be invalid.

I would delete this line:
$(this).find(".img-swap").live('click', function() {
What is it's purpose? You can swap this image right after the first click, right?
Also, make sure that .img-swap is inside the tag with class test_toggle.
You are using:
$(this).find(".img-swap")
find() searches only in children of selected element.
If it's not nested use
$(".img-swap")
instead of:
$(this).find(".img-swap")

I have re-written the js, but not tested. Can I nest clicks?
$(".test_toggle").click(function(){
$.find(".img-swap").click(function(){
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});

Related

jQuery hide element when click in datepicker

I have a hidden div which will be shown on a button click and hide when i click every where else in page.
Now the problem is here:
Inside my div I have datepickers whenever I click on next/prev or select date,div slides up. How can I prevent that?
The code is here:
$(document).click(function(evt) {
if(evt.target.id!='btn' )
if($('#div').is(':visible')) {
$('#div').slideUp();
}
});
$("#div").click(function(e) {
e.stopPropagation();
return false;
});
$('#btn').click(function () {
if($('#div').is(':visible')) {
$('#div').slideUp();
}
else{
//initialize controls
$('#div').slideDown();
}
});
Update:
jsfiddle added.
Please check my js fiddle
I have added date picker id #ui-datepicker-div" for stop propagation, and it's worked.
$(document).click(function(evt) {
if(evt.target.id!='btn' )
if($('#div').is(':visible')) {
$('#div').slideUp();
}
});
$( "#datepicker" ).datepicker();
$("#div, #ui-datepicker-div").click(function(e) {
e.stopPropagation();
return false;
});
$('#btn').click(function () {
if($('#div').is(':visible')) {
$('#div').slideUp();
}
else{
//initialize controls
$('#div').slideDown();
}
});
you have to slideUp your required div if you click anywhere in your document body except your button 'btn', your div itself AND div children:
$(document).click(function(e) {
if ( e.target.id != 'btn' && e.target.id != 'div' && !$('#div').find(e.target).length) {
if($('#div').is(':visible')) {
$('#div').slideUp();
}
}
});
In your document.ready you made mistake in if block, I modified it as
if(evt.target.id!='btn' ){
if($('#div').is(':visible')) {
$('#div').slideDown();
}
}
Also try to avoid using id as 'btn' as it this id or class will make confusion if you use more css in your design
Here is another version of the same problem. Use some common class for those elements that wouldn't hide your div. Hope it will help you:
HTML :
<html>
<body>
<div id="container" style="display:none">
<input type="date" class="prevent-click">
</div>
<button onclick="display()" class="prevent-click">click</button>
</body>
</html>
JS :
var display = function () {
$("#container").toggle();
$("body").off("click").on("click", function (event) {
if ($(event.target).hasClass("prevent-click")) {
return;
}
$("#container").hide();
});
}

Removing class if click outside of div (targetting class)

I have a menu where user clicks on link and list appears via .addClass( "show-nav" ).
Here is jsFiddle with JS code:
jQuery(".nav-js-trigger").each(function(){
this.onclick = function() {
var hasClass;
hasClass = jQuery(this).next().hasClass( "show-nav" );
jQuery('.show-nav').removeClass('show-nav');
if (hasClass === false) {
jQuery(this).next().addClass( "show-nav" );
}
}
});
I want to remove the class show-nav if the user clicks outside of the div with class show-nav. How do I do this?
I have seen examples of e.target div ID but not class, particularly not a scenario like this.
You can add an listener to the element with an event.stopPropagation() on it, and another listener to the body, to capture this event if not intercepted before.
Something like this:
$(".show-nav").on("click", function(event){
event.stopPropagation();
});
$("body").on("click", function(event){
$(".show-nav").hide(); // or something...
});
To simplify your use-case, here is a JSFiddle.
$(".trigger").on("click", function(event)
{
$(".menu").toggle();
event.stopPropagation();
});
$(".menu").on("click", function(event)
{
event.stopPropagation();
});
$(document).on("click", function(event)
{
$(".menu").hide();
});
.menu
{
display: none;
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
menu
<div class="menu">Hello</div>
$(document).on("click", function(e) { if ($(e.target).is(".trigger") === false) {
$(".menu").hide();
}
});

Change bgcolor on toggled tr and on key shortcut

I have the following toggle function filter() where I display the childrow of a table when the <tr> parent is being clicked. In this function I've also included a key shortcut, so whenever ALT+A is pressed all the childrows are displayed.
In addition I have another script, mouseover(), where the background color of the parent tr is changed to #2C4367 hover.
So here's my question: How can I toggle the background-color of a tr parent whenever I expand (click on) it and back to normal when it is closed. This function should also work on all tr parents when the key shortcut is pressed, so the background color of all parent tr's is changed when the shortcut is being pressed.
I hope I made myself clear. Otherwise please say so and I will try to elaborate.
Toggle filter() script:
$(document).ready(function mouseover(){
$(".parent").hover(function(){
$(this).css("background", "#2C4367");
$(this).css("color", "#FFFFFF");
},
function(){
$(this).css("background", "#FFFFFF");
$(this).css("color", "#000000");
});
});
Change bgcolor mouseover() script:
$(document).ready(function filter() {
$('table.detail').each(function() {
var $table = $(this);
$table.find('.parent').click(function() {
$(this).nextUntil('.parent').toggle(); // must use jQuery 1.4 for nextUntil() method
}); /// Below is toggle on image
var $childRows = $table.find('tbody tr').not('.parent').hide();
$("img.pushme").toggle(function funcVis() {
$childRows.show();
},
function() { $childRows.hide();
});
shortcut.add("Alt+A",function(){ funcVis() }); /// Shortcut functions
shortcut.add("Alt+N",function(){ expandform() }); /// Shortcut functions
});
});
Create a CSS class that defines the background-color change, and apply or remove it with
$(target).parent().toggleClass('yourclass');
Insert this line wherever the expand is triggered.
Solved!
JSFiddle
function toggle(it) {
if ((it.className == "") || (it.className == "rowactive")) {
it.className = "rownotactive";
} else {
it.className = "rowactive";
}
}
$(document).ready(function filter() {
$('table.detail').each(function () {
var $table = $(this);
$table.find('.parent').click(function () {
$(this).toggleClass('rowactive');
$(this).nextUntil('.parent').toggle();
}); /// Below is toggle on image
var $childRows = $table.find('tbody tr').not('.parent').hide();
$("img.pushme").toggle(function funcVis() {
$("tr.parent").addClass('rowactive');
$childRows.show();
},
function () {
$("tr.parent").removeClass('rowactive');
$childRows.hide();
});
shortcut.add("Alt+N", function () {
expandform()
}); /// Shortcut functions
});
});

Toggle element's class by ID

I’m trying to change the class of an element when it is clicked on from one value A to value B and then from value B back to value A when it is clicked a second time. I found some code on here that allowed me to change it once, but not a second time. (See original here).
Here is the original code:
<script type="text/javascript">
function changeClass() {
document.getElementById("MyElement").className += " MyClass";
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/(?:^|\s)MyClass(?!\S)/g, '')
}
</script>
And here is my code:
<script type="text/javascript">
function changeClass() {
if (document.getElementByID("arrow").className == "arrowdown") {
document.getElementById("arrow").className.replace(/(?:^|\s)arrowdown(?!\S)/g, 'arrowup')
}
elseif(document.getElementByID("arrow").className == "arrowup") {
document.getElementById("arrow").className.replace(/(?:^|\s)arrowup(?!\S)/g, 'arrowdown')
}
}
</script>
$('#arrow').toggleClass('arrowup arrowdown');
Why not simply use jQuery toggleClass instead along with a id selector?
$('#arrow').toggleClass('arrowup');
$('#arrow').toggleClass('arrowdown');
And save yourself debugging and a few lines of code!
Check this FIDDLE
Its far easier with JQuery..
$(function() {
var i = 0;
$('div').on('click', function() {
i++;
if( i % 2 == 0){
$(this).addClass('arrowup').removeClass('arrowdown');
}
else{
$(this).addClass('arrowdown').removeClass('arrowup');
}
});
});​
just use jquery addClass() and removeClass() or even better the toggleClass inside your click event
<div id="elemID" class="class1">
</div>
function changeClass()
{
$("#elemID").toggleClass("class1");
$("#elemID").toggleClass("class2");
}
REF's
http://api.jquery.com/addClass/
http://api.jquery.com/removeClass/
http://api.jquery.com/toggleClass/
Cheers
I faced something similar to this today. In my code for each feature the user would express his opinion by pressing thumbs up or thumbs down. The selected thumb icon would have a brighter color, so when the user would click the thumbs up icon, the thumbs up icon would turn green and the thumbs down icon (if it were green) would turn black.
I solved it using jQuery:
$(document).ready(function () {
$('#vote-yes-#(Model.ProductReviewId)').click(function () {
setProductReviewHelpfulness#(Model.ProductReviewId)('true');
$('#1vote-yes-#(Model.ProductReviewId)').toggleClass('green');
$('#1vote-no-#(Model.ProductReviewId)').removeClass('green').addClass('black');
});
$('#vote-no-#(Model.ProductReviewId)').click(function () {
setProductReviewHelpfulness#(Model.ProductReviewId)('false');
$('#1vote-no-#(Model.ProductReviewId)').toggleClass('green');
$('#1vote-yes-#(Model.ProductReviewId)').removeClass('green').addClass('black');
});
});

hiding div when clicked outside the div

Please look at the code here : http://jsbin.com/esokic/10/edit#source
When I click on customer support a div is shown
What I want is when someone clicks out of the div, the div should hide, I tried a couple of things, but they don't seem to work..
$(document.body).one("click", function() {$(".cust-support-outer").hide();
});
Also:
$("body").click(function(e){
if(e.target.className !== "csupport-drop")
{
$(".cust-support-outer").hide();
}
});
Would appreciate any help...
--Arnab
Arnab
I did this change in your js and worked
try this, use this js code
$(function(){
$(".csupport-drop").click(function(){
$(".csupport-drop").addClass("active-drop-tab");
$(".cust-support-outer").show();
return false
});
$(document).bind("click", function(e) {
if(!$(e.target).hasClass("get-daily-alerts-outer")){
$(".get-daily-alerts-outer").hide()
}
});
$(".close").click(function(){$(".get-daily-alerts-outer").hide();
return false
});
$(".get-deal-alerts").click(function(){$(".get-daily-alerts-outer").show();
return false
});
});
I just changed how you bind the "click" event to the document and pass the Event object to the function so you can check over what element the click event was fire.
Try:
var mouse_is_inside = false;
$(document).ready(function()
{
$('.cust-support-outer').hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").mouseup(function(){
if(! mouse_is_inside) $('.cust-support-outer').hide();
});
});
Bind this to body
$("body").click(function() {
if ($(this).attr("class") == "cust-support-outer") {
// inside
} else {
// not inside
}
});

Categories