Targeting a clicked element - javascript

Fiddle
I am trying to make a button that toggles between making an img grayscale and normal. I need to find a way to properly target the button if it was clicked. I tried adding a class on click and then targeting that class. I also tried this.
$('.switch').on("click", function() {
if($(this).attr('data-click-state') == 1) {
$(this).attr('data-click-state', 0)
$(this).siblings('img').css("-webkit-filter", "grayscale(100%)");
} else {
$(this).attr('data-click-state', 1)
$(this).siblings('img').css("-webkit-filter", "none");
}
});
Why the button doesn't toggle between color and grayscale versions?
apparently the problem isn't in my jQuery but in my html, so is it not possible to use this jquery on a checkbox label?

When you press the button once, it detect two clicks. I set an alert outside the if statement and I would get it twice per click, so your problem lies with that.
I'm still inspecting it, but that the issue right now, need to figure out why it is occurring, will update.
Update:
Yes sir, that was the cause that I stated in the comments... Here is a fixed, and you can mess with it however you like.
$('#cmn-toggle-1').on("click", function() {
if($(this).attr('data-click-state') == '1') {
$(this).attr('data-click-state', '0')
$(this).parents().siblings('img').css("-webkit-filter", "grayscale(100%)");
}
else {
$(this).attr('data-click-state', '1')
$(this).parents().siblings('img').css("-webkit-filter","");
}
});
New HTML SNIP:
<div class="switch">
<input id="cmn-toggle-1" class="cmn-toggle cmn-toggle-yes-no" type="checkbox" data-click-state="1">
<label for="cmn-toggle-1" data-on="Color" data-off="B&W" data-click-state="1"></label>
</div>
As you can see if you look at the input, I added in the data-click-state="1"

Related

Hide DIV when input field is blank

I wonder if you could help me with an issue.
I am building a content template for an events page, that pulls data through using Advanced Custom Fields.
I have a field in the admin side which will be filled out when adding a new event. The field is called show_info with the ID #acf-editor-46.
On some events however this will be left blank, but the DIV that wraps around the content on the frontend will still show on the template, the DIV has the class .show-info-wrapper.
I would like it so when the show_info field is blank, the DIV .show-info-wrapper does not display on the front end.
I have made some progress from browsing around, you can see the code I have so far here:
HTML (Just a quick testing set up):
<textarea id="acf-editor-46" class="wp-editor-area" aria-hidden="true">1111</textarea>
<div class="show-info-wrapper">CONTENT</div>
JavaScript + jQuery:
$(document).ready(function() {
if($('#acf-editor-46').val() == '' ){$('.show-info-wrapper').hide();}
$('#acf-editor-46').on('change' , function() {
if( this.value != ''){
$('.show-info-wrapper').show();
}
else{
$('.show-info-wrapper').hide();
}
});
});
It works on JSFiddle (http://jsfiddle.net/ha2nedfb/), however, it seems that on my WordPress site as the input and the DIV are not on the same DOM, it does not work.
Could anyone help me with this?
Thank you!
Just change the event of #acf-editor-46 to input.
$(document).ready(function() {
if($('#acf-editor-46').val() == '' ){$('.show-info-wrapper').hide();}
$('#acf-editor-46').on('input' , function() { // Just change event to input
if( this.value != ''){
$('.show-info-wrapper').show();
}
else{
$('.show-info-wrapper').hide();
}
});
});
if (!$("#acf-editor-46").val()) {
// textarea is empty
}
try this to check textarea is empty or not
You can delegate event if textarea is rendered later.
$(document).on('change', '#acf-editor-46', callback);
Links:
https://api.jquery.com/on/
https://learn.jquery.com/events/event-delegation/
Assuming the <textarea> and <div> are really siblings in this very order (your text contradicts the example) & if you're OK with adding a placeholder to the textarea & you only need new-ish browsers, there is a pure CSS solution:
<textarea ... placeholder=" "> </textarea>
.show-info-wrapper {
display: block;
}
.wp-editor-area:placeholder-shown + .show-info-wrapper {
display: none;
}
Here's a pen.

HTML and JavaScript: Change button text (Toggle)

I need to change a button's text, however I think the issue I don't understand is how to change it back using separate files. I need to use jQuery to toggle pictures. This will hide the image and show the image. The button is "hard coded" I think in both the HTML and JavaScript.
The button is showing "hide" to initially hide the image. Once the button is clicked the image disappears and the button's text turns to "Show". However it will not turn back to "hide".
HTML:
<img src="sky.jpg" id="sky">
<input type='button' onclick="js/toggle.js" id="skybutton" value="Hide">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/toggle.js"></script>
JavaScript:
$('#skybutton').click(function() {
$("#sky").toggle();
$(skybutton).val('Show');
});
Welcome to stackoverflow Shepard!!
You need little bit of logic in your javascript in order to make this work both ways:
<img src="sky.jpg" id="sky">
<input type='button' onclick="js/toggle.js" id="skybutton" value="Hide">
Here in the click function is where you need magic to happen:
Try this code:
$('#skybutton').click(function() {
$("#sky").toggle();
if($(this).val() === 'Hide'){
$(this).val('Show');
}else{
$(this).val('Hide');
}
});
So what is happening above is that you already have a click function attached to the button so with in the function you can refer to that button as this and you can check what the value of the button is.
Your if statement goes hey button if your value is 'Hide' change the value to 'Show' and else your value must be 'Show' so change it back to 'Hide' let me know if I can clear anything else up for you. Good luck with the project
You can achieve this using an if else statement say:
$('#skybutton').click(function() {
If($(this).val() == "hide") {
$("#sky").hide();
$(this).val("Show")
} else {
$("#sky").show();
$(this).val("hide")
}
});
In support of I am Cavic, just a more readable version
$('#skybutton').click(() => {
$("#sky").toggle()
if ($(this).val() === "hide") {
$(this).val("show")
return
}
$(this).val("hide")
})

Jssor list-slider and X-Editable

I have a Jssor list slider and I would like to make the thumbnail text editable in place with X-Editable:
example
Both functions work on the page together with separate elements, but I cannot find a way of causing the link text to become editable.
There are no errors, the text element simply does not show the pop-up editable box.
I presume this is because the class="t" declaration informs Jssor to control the thumb div interfering with X-editable's attempt to do the same.
X-Editable requires that the editable text be wrapped in an element:
superuser
But this seems to be interfered with by Jssor.
Can anyone point me in the right direction?
------------------UPDATED in response to answer------------------
Thanks for taking the time to help me out :)
I was unable to change the default behaviour from on click to onmousedown in the x-editable library, but I did find a work around to allow activation of the editable element with the click of another element external to the slider container.
In the body:
$(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('#doit').click(function(e){
e.stopPropagation();
$('#username').editable({
send: 'never',
title: 'Enter text',
placement: 'right',
toggle: 'manual',
display: function(value) {
$('#username').text(value);
}
});
$('#username').editable('toggle');
});
});
...and the elements:
<span id="username" data-type="text" data-pk="1" data-url="/post" data-title="Enter username">superuser</span>
<a id="doit" href="#">testlink</a>
If the span is outside of the slider container clicking the testlink functions as expected and opens the pop-up editor input field, but once it is placed inside the slider:
<div class="t">
<span id="username" data-type="text" data-pk="1" data-url="/post" data-title="Enter username">superuser</span>
</div>
...there is no response.
I looked for the function you highlighted and think I found the one you meant, 'ContentClickEventHandler', but clearing this function did not solve the problem.
Thanks again for you help, and for releasing this wonderful product to the likes of me :D
Please try the following 3 approaches.
I guess X-Editable detects click event to make an element editable. If you can revise the library, please change the event from click to mousedown.
Not sure it would work or not, please have a good try.
Add nodrag="true" for the link element.
Open jssor.slider.js, replace
function SlidesClickEventHandler(event) {
if (_LastDragSucceded) {
$Jssor$.$StopEvent(event);
var checkElement = $Jssor$.$EventSrc(event);
while (checkElement && _SlidesContainer !== checkElement) {
if (checkElement.tagName == "A") {
$Jssor$.$CancelEvent(event);
}
try {
checkElement = checkElement.parentNode;
} catch (e) {
// Firefox sometimes fires events for XUL elements, which throws
// a "permission denied" error. so this is not a child.
break;
}
}
}
}
with
function SlidesClickEventHandler(event) {
}

What causes jQuery click event not always to fire?

I have the following script. The HTML is not dynamically added. 99% of the time, the confirm popup will open and the data will be posted if confirmed, but every now and then, the checkbox visually changes state, but the confirm popup does not open. I've witnessed this on Firefox 34.0.5 running on Windows 7, and haven't yet tested enough on other browsers.
What might cause this to happen, and how can it be prevented?
EDIT. It happens all the time when I go to the page and quickly click the checkbox.
<input type="checkbox" checked="" id="makePublic">
$(function() {
$("#makePublic").click(function(e){
if($(this).is(":checked")){
var status=1;
var message='Are you sure you wish to make this project public?';
}
else {
var status=0;
var message='Are you sure you wish to make this project private?';
}
if(window.confirm(message)) {
$.post('update.php',{id:$('#id').val(),status:status});
}
else {e.preventDefault();
return;
}
});
});
EDIT. It happens all the time when I go to the page and quickly click the checkbox.
Then you should disable the element until your javascript has finished. The issue is that the checkbox is visible without the event being attached. The best option in my opinion is to disallow the click (by setting it disabled or hiding etc) until after the event has been attached.
<input type="checkbox" checked="" id="makePublic" disabled="disabled">
$(function() {
$("#makePublic").click(function(e){
if($(this).is(":checked")){
var status=1;
var message='Are you sure you wish to make this project public?';
}
else {
var status=0;
var message='Are you sure you wish to make this project private?';
}
if(window.confirm(message)) {
$.post('update.php',{id:$('#id').val(),status:status});
}
else {e.preventDefault();
return;
}
});
$("#makePublic").prop('disabled','');
});

Radio Button "Select" Toggle issue

I am trying to make a very very simple script that checks to see if a certain radio button option is clicked, and if so, shows another set of fields (this works fine), but if you unselect that radio button option, it hides the extra set of fields (seemingly simple, but does not work for me!)
Also I am newish to JS/JQuery so debugging this has been a struggle! Thanks for any help :)
My HTML radio button that triggers the fields display - imagine there are 6 other radio button options with this (each classed with [class="otherFund"]).
<input type="radio" name="ItemName1" id="Relief1" value="Daughters of Penelope Charitable Relief Fund" onclick="set_item('DOP-Relief-Fund', 8)" onchange="relief_fund_handler()" />
Here is the text and field and I want to toggle with the above button's selection
<p id="Earmark1" style="display: none;">
<strong>Please designate below what relief fund you would like your <em>DOP Charitable Relief</em> donation to go towards (see bulleted examples above).</strong><br />
<strong>Earmarked for <span class="required">*</span>:</strong><input type="text" name="Earmark1" id="Earmark1" size="50" />
</p>
And here are my JS attempts...
Attempt 1:
function relief_fund_handler() {
var relief_elem = document.getElementById("Relief1"),
earmark_elem = document.getElementById("Earmark1"),
donate_elem = document.getElementById("ItemName1");
if (relief_elem.checked) {
earmark_elem.setAttribute("style", "display: inline;");
} else if (".otherFund".checked) {
earmark_elem.setAttribute("style", "display: none;");
}
}
attempt 2:
function relief_fund_handler() {
var relief_elem = document.getElementById("Relief1"),
earmark_elem = document.getElementById("Earmark1"),
donate_elem = document.getElementById("ItemName1");
if (relief_elem.checked) {
earmark_elem.setAttribute("style", "display: inline;");
} else {
earmark_elem.setAttribute("style", "display: none;");
}
}
attempt 3:
$("#Relief1:checked")(
function() {
$('#Earmark1').toggle();
}
);
On attempt #3, I have also replaced the :checked with .click, .select, .change and none have worked... Thanks for any help! :)
Try this:
$("input.otherFund").change(function() {
$('#Earmark1').toggle($(this).attr('id') == 'Relief1');
});​
Try removing all of the events off of the radio button like this:
<input type="radio" name="ItemName1" id="Relief1" value="Daughters of Penelope Charitable Relief Fund" />
And using the following jquery script:
​$(function(){
$("#Relief1").change(function(){
$(this).is(":checked") ? $("#Earmark1").show() : $("#Earmark1").hide();
});
});​
You could iterate through each radio button and assign an event handler to each radio button, so when selected it shows the other fields and when deselected it hides the other fields. The code below may help you arrive at the correct answer.
// Iterate the radio buttons and assign an event listener
$('input[name="ItemName1"]').each( function() {
// Click Handler
$(this).live('click', function() {
// Check for selected
if ( $(this).is(':checked') )
{
$('#EarMark1').show();
}
else
{
$('#EarMark1').hide();
}
});
});
It's not perfect, nor is it the most elegant solution. With some tweaking it should point you in the right direction.
thank you to everyone!!! I ended up using kennypu's example - the ":checked" seemed to work fine even though it is a radio button. I had to make some tweaks to it, and ended up with 2 separate functions instead of the "else". For some reason the other examples were not working for me - although I highly doubt it has to do with your code, and likely has to do with other things going on in the page. Since we're using an external form/database handler, we need to keep the events and other code there.
Here's what ended up working..
$(function(){
$("#Relief1").change(function(){
if($(this).is(":checked")) {
$("#Earmark1").show();
}
});
});
$(function(){
$("#Radio1, #Radio2, #Radio3, #Radio4, #Radio5, #Radio6, #Radio7").change(function(){
if($(this).is(":checked")) {
$("#Earmark1").hide();
}
});
});
Pretty clunky, but I got it to work how I needed. Thank you to everyone who contributed, it helped quite a bit.
Try:
<script>
var r=$('input[name="ItemName1"]).is(:checked);
if(r)
{
alert("Item is checked");//replace with any code
}
</script>
if you're already using jQuery, this is simple as using .show() and .hide():
$('#Relief1').on('change',function() {
if($(this).is(':checked')) {
$('#Earmark1').show();
} else {
$('#Earmark1').hide();
}
});
example fiddle: http://jsfiddle.net/x4meB/
also note, don't use duplicate ID's, they are meant to be unique (in this case, you have a dulpicate #Earmark1 for the p tag and span). Also, in the example fiddle, I changed it to a checkbox instead of a radio since You can't uncheck a radio if there is only one option.

Categories