Jquery child div selection - javascript

I'm using switchy http://lou.github.io/switchy/ and it uses animate-color.js
I have more than one, unlike their page, everytime one gets toogle all of them turn green, how can I prevent this so one gets toogle only
$(function () {
$('.binary').switchy();
$('.binary').on('change', function () {
// Animate Switchy Bar background color 7cb15b
var bgColor = '#ebebeb';
if ($(this).val() == '1') {
bgColor = '#7cb15b';
} else if ($(this).val() == '0;') {
bgColor = '#ebebeb';
}
$('.switchy-bar').animate({
backgroundColor: bgColor
});
// Display action in console
var log = 'Selected value is "' + $(this).val() + '"';
$('#console').html(log).hide().fadeIn();
});
});
You can see what I mean here www.niors.com

Here:
$('.switchy-bar').animate({
backgroundColor: bgColor
});
you get ALL switchy-bar from document. So you need to find context you need, i.a. this way:
$(this).parent().find('.switchy-bar').animate({
backgroundColor: bgColor
});
#(this) -> select
$(this).parent() -> wrapper (.field)
and then search for switchy bar for changed select.
Of course, for better performance and readibility it'd be great to cache $(this) in some variable at the beginning of callback function.
Something like this:
$(function () {
$('.binary').switchy();
$('.binary').on('change', function () {
var $select = $(this);
var selectedValue = $select.val();
// Animate Switchy Bar background color 7cb15b
var bgColor = {
'0': '#ebebeb',
'1': '#7cb15b'
};
$select.parent().find('.switchy-bar').animate({
backgroundColor: bgColor[ selectedValue ]
});
// Display action in console
var log = 'Selected value is "' + selectedValue + '"';
$('#console').html(log).hide().fadeIn();
});
});

change
$('.switchy-bar').animate({
backgroundColor: bgColor
});
to
$(this).parent().find('.switchy-bar').animate({
backgroundColor: bgColor
});
the idea is to just change one switchy-bar which is related to element you are clicking or selecting for...

Related

Adding javascript causing divs not getting displayed on website

I have a select field ('5f01264e722ae') with which I would like to change the color of a text print ('.sw_poster_text2'). With a little help from another member, I uploaded the script below. However, as soon as I undo the // from the .change function my website no longer displays the print, image on which to print, and then select options. Any idea how to fix this? Here is a link of the working page: https://www.horseglamour.com/product/pagony-concours-zadeldek/
Thank you for your help.
<script>
jQuery(document).ready(function() {
var fieldId = "5f0124e773aa8"; // Change this
var defaultText = "my name"; // Change this
if (!jQuery('input[data-field-id="' + fieldId + '"]').length)
return;
var $el = jQuery('<div class="sw_poster_text2">').html(defaultText);
$el.appendTo(jQuery('.woocommerce-product-gallery--with-images'));
jQuery(document).on('change keyup', 'input[data-field-id="' + fieldId + '"]', function() {
var v = jQuery(this).val() || defaultText;
jQuery('.sw_poster_text2').html(v);
}).trigger('change');
//$("select[data-field-id='5f01264e722ae']").change(function() {
//var color = $(this).find('option:selected').data('wapf-label')
//$(".sw_poster_text2").css("color", color);
//});
});
</script>
You can alter commented out part of your script to following:
jQuery("select[data-field-id='5f01264e722ae']").change(function() {
var color = jQuery(this).find('option:selected').data('wapf-label')
jQuery(".sw_poster_text2").css("color", color);
});
or if you perfer $ to access jQuery you can reference to it in callback https://api.jquery.com/jquery.noconflict/
jQuery(document).ready(function($) {
var fieldId = "5f0124e773aa8"; // Change this
var defaultText = "my name"; // Change this
if(!jQuery('input[data-field-id="'+fieldId+'"]').length)
return;
var $el = jQuery('<div class="sw_poster_text2">').html(defaultText);
$el.appendTo(jQuery('.woocommerce-product-gallery--with-images'));
jQuery(document).on('change keyup','input[data-field-id="'+fieldId+'"]',function(){
var v = jQuery(this).val() || defaultText;
jQuery('.sw_poster_text2').html(v);
}).trigger('change');
$("select[data-field-id='5f01264e722ae']").change(function() {
var color = $(this).find('option:selected').data('wapf-label')
$(".sw_poster_text2").css("color", color);
});
});

Store a selector in a variable Javascript and then use a method on it

I have check some others post, and document myself but I dont know what is the problem here.
I have 2 image (would like to have like 20 at the end) where you can click on an icon and show and hide and image in the webpage. If you click on image A it should show image A, if you click on image B image A should hide and image B should be sown.
var firsttime = 1;
var $lastletter;
$(function() {
$('#A').click(function() {
if (firsttime = 0){
$lastletter.toggle();
$('#AL').toggle();
$lastletter = $( '#AL' );
}
else
{
firsttime = 0;
$('#AL').toggle();
$lastletter = $( '#AL' );
}
});
});
$(function() {
$('#B').click(function() {
if (firsttime = 0){
$lastletter.toggle();
$('#BL').toggle();
$lastletter = $( '#BL' );
}
else
{
firsttime = 0;
$('#BL').toggle();
$lastletter = $( '#BL' );
}
});
});
This is the solution im using:
$(function() {
$('.imgLetter').click(function() {
if (lastletter != this.id) {
$('#' + lastletter + 'L').toggle();
lastletter=this.id;
}
$('#' + this.id + 'L').toggle();
});
});
Assuming you're conventionally assigning the "last letter" by appending an "L" to the ID: this could get a lot simpler. Decorate all of your #<x> elements with a class name that makes it easy to select all of them at once. I'm going to choose "letter".
I don't think you even need to track the "first time". It sounds like you just want one element to toggle another. That would look like:
$(function() {
$('.letter').click(function() {
$('#' + this.id + 'L').toggle();
});
});

How do I run a function from a variable?

I'm trying to run a function from a variable I've defined although it's not working.
Here is an example of what I mean:
$(document).ready(function(){
function red () {
alert("You chose the color red");
}
function blue () {
alert("You chose the color blue");
}
$(window).resize(function() {
var colorvalue = "blue" + "();";
return colorvalue
});
});
If someone could correct my faulty logic that would be helpful, thanks.
SOLVED! FULL SOLUTION HERE
function red () {
alert("You chose the color red");
}
function blue () {
alert("You chose the color blue");
}
$(document).ready(function(){
$(window).resize(function() {
var colorvalue = "blue";
var callable = window[colourvalue];
callable();
});
});
The following code will work absolutely
$(window).resize(function() {
var callable = window["blue"];
callable();
});
Try it
Try this:
var red = function{ alert("You chose the color red"); };
var blue = function{ alert("You chose the color blue"); };
$(document).ready(function(){
$(window).resize(function() {
var colorvalue = window["blue"];
return colorvalue();
});
});
This way you can evaluate the target function to call without using eval.
you should try
return eval(colorvalue);
Set up an object with your functions as methods. (This avoids multiple globals.)
var colour = {
red: function{ ... },
blue: function{ ... }
}
Then call colour[myOption] where myOption is set to be "blue" or "red" somehow (probably by the user).
Put your function out of you Document ready function. like below
function red() {
alert("You chose the color red");
}
function blue() {
alert("You chose the color blue");
}
$(document).ready(function () {
$(window).resize(function () {
var colorvalue = "blue" + "();";
return eval(colorvalue);
});
});
if you want to use in document ready then use like onclick to particular id : exp: $( "#target" ).click();
REF
Just do:
var colorvalue = blue;
return colorvalue();
Though note that the alert() function doesn't return anything, and your functions aren't even returning anything, so right now your functions will return undefined. Perhaps you meant to define them like:
function blue () {
var msg = "You chose the color blue";
alert(msg);
return msg;
}
you could try:
var red = function(){
// doSomething
}
var blue = function(){
//doSomething
}

How to remove null from my Javascript

So, here's my script:
$(function () {
// define this here because we're changing the ID
var $twitter = $('twitter');
// bind to select inside iframe
$('#iframe').on('load', function () {
$(this).contents().find('#cds').change(function () {
var selectVal = $(this).val();
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$twitter.attr("id", url);
}).change(); // trigger change to get initial value
});
});
Basically, it takes the selected value from my select box, and outputs it into a twitter link. The problem is, when nothing is selected, it outputs "null", and I was wondering if there was a way to detect this, and echo something else.
Try this:
var selectVal = $(this).val() || 'default value';

referencing this inside a function

Given the code (a lot of it stripped out)
// A data set
$.DataArea = function() {
// Default options
$.extend(this, {
'class': "DataSet",
'bars': new Array(),
'container': null,
'containerId': null,
'gridsize': 20,
'width': 400,
'height': 400,
'currentSelectedBar': 0
});
// Add a bar to this object
this.addBar = function(startDate, endDate, label, styleID) {
// When the bar is clicked
$('#' + barID).click(function() {
alert($(this).currentSelectedBar);
if (this.currentSelectedBar != undefined)
$('#' + this.currentSelectedBar).fadeIn("slow");
this.currentSelectedBar = barID;
$('#' + barID).fadeTo("slow", 0.5);
});
}
When I alert($(this).currentSelectedBar); it always comes out as undefined, it's not setting the value properly. Any ideas why this might be?
The idea is when you click on a bar, it fades it out, and when you click another the last bar to fade out fades in as well.
Assuming you are calling addBar on an instance of DataArea, your code should be:
// Add a bar to this object
this.addBar = function(startDate, endDate, label, styleID) {
var self = this;
// When the bar is clicked
$('#' + barID).click(function() {
alert(self.currentSelectedBar);
if (self.currentSelectedBar != undefined)
$('#' + self.currentSelectedBar).fadeIn("slow");
self.currentSelectedBar = this.id;
$(this).fadeTo("slow", 0.5);
});
}
Inside the click handler, this will refer to the DOM element '#' + barID. But the properties are assigned to some other element and not that DOM element.
The this in your callback function refers to the element that rises the event : in that case $('#' + barID).
I guess you want to access the this that you extended. In that case, you should write something like that :
this.addBar = function(startDate, endDate, label, styleID) {
var self = this
// When the bar is clicked
$('#' + barID).click(function() {
alert($(self).currentSelectedBar);
if (self.currentSelectedBar != undefined)
$('#' + self.currentSelectedBar).fadeIn("slow");
self.currentSelectedBar = barID;
$(this).fadeTo("slow", 0.5);
});
}
var that = this;
$('#' + barID).click(function() {
alert(that.currentSelectedBar);
if (that.currentSelectedBar != undefined)
$('#' + this.currentSelectedBar).fadeIn("slow");
that.currentSelectedBar = barID;
$('#' + barID).fadeTo("slow", 0.5);
});
Cache the value of this outside the click function. inside the click function, the context this is the DOM node that was clicked.
It looks like you're having an issue with the behavior of jQuery.
$('#' + barID).click(function() { remaps the definition of this, but having attempted to add attributes to it previously will have no effect because the definition of this has been overwritten.
As mentioned by recmashak you can put the original this into a variable and then use it when you do your alert

Categories