jQuery Checkbox/Target _Blank - javascript

I have the following jQuery on my website:
$(function() {
$('#newtab').toggle(function() {
$('a').attr('target', '_blank');
},
function() {
$('a').removeAttr('target');
});
});
The code is for a checkbox that toggles the target of links on my page (when checked, links open in a new tab (target="_blank"), otherwise, they open in the same page.
I have two issues:
I want to make it so only links in a particular div are affected by the toggle (I essentially just don't want links in my menu to be affected by it).
When clicking the checkbox, the check is never shown for some reason. I have <input type="checkbox" id="newtab" /><label for="newtab">Open links in new tab</label>
on my page which shows the checkbox (unselected). When I click on it, it changes the target attribute, but the checkbox never appears to be selected; it still shows the empty box. Clicking the checkbox again removes the target attribute as expected.
Thanks.

This should solve your problem: http://jsfiddle.net/UJMgQ/2/
$(function () {
$('#newtab').click(function () {
if ($(this).is(':checked')) {
$('#wanted a').attr('target', '_blank');
} else {
$('#wanted a').removeAttr('target');
}
});
});
To limit the a's that are selected just change #wanted to what ever div(container) the a's you want are in. It works like a css selector.

For part 1: $('.divYouWant a').attr(...) will limit it, just like a CSS selector would.
For part 2: According to the docs of toggle() "The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.". If you don't want that, either use .click(), or just set $('#newtab').checked equal to one in the selected function, and 0 for the unselected function.

Try: $('#mydiv').find('a').attr('target', '_blank');
I think toggle wants you to return true to make the click event propagate to the checkbox. Not sure, but checking the docs may be in order here...
Nevermind, docs say that toggle prevents propagation. Perhaps use something like $.change() instead, and use the value of the checked property to set the values you want.

Related

Why can't jquery remove these classes?

I have created a series of elements that when you click on any one of them, they will expand, pushing the other elements out of the way. Initially if you clicked on it again the element would contract, but now I want to take the close functionality and put it in a button with in the element.
Initially when you click on the element, I use jQuery to add a number of classes to a variety of elements.
$(".left > .elem").click(function () {
$(this).addClass("expand");
$(this).parent().addClass("WithLarge");
$(this).children(".bar").addClass("visible");
$(this).children(".reduce_button").addClass("visible");
$(".right").addClass("shift_right");
});
When I click the close button I would like to remove those classes.
$(".reduce_button").click(function () {
$(this).parent().removeClass('expand');
$(this).parent().removeClass("WithLarge");
$(this).parent().children(".bar").removeClass("visible");
$(this).parent().children(".reduce_button").removeClass("visible");
}
The problem is, those classes aren't budging.
You can try it out on the JSFiddle
Click on the yellow box(".left > .elem"), it expands pushing the others out of the way, click on the red box(".reduce_button"), and nothing happens. I tried
console.log($(this).parent().hasClass('expand'));
$(this).parent().removeClass('expand');
console.log($(this).parent().hasClass('expand'));
to see if it has been removed. It returns false, even though the class is still there.
Why can't I remove these classes?
You ARE removing the class. But, the click on the .reduce_button is also triggering the .elem click event, which adds the class back again.
EDIT:
As commented below by j08691, you can add stopPropagation to keep the event of going on to the next listener, like:
$(".reduce_button").click(function (e) {
$(this).parent().removeClass('expand');
e.stopPropagation();
...
Here is your fiddle updated: http://jsfiddle.net/HybHK/9/

Jquery open and close within a parent div

The title does not explain that well, essentially I have 8 divs the same, with the same class for css styling.
They all have hidden content, I want to be able to only expand one div at a time without using different classes or identifiers for each div and hidden content.
I have tried to display this on Jsfidle using two divs the same , however I can't even get it to fire on jsfiddle for some reason
http://jsfiddle.net/dAXJ2/8/
$(document).on('click',".servicereadmore",function() {
//var x = $(this).closest('div').attr('class')
//$('.hiddenservices').parent(x).slideDown(1000);
$('.hiddenservices').slideDown(1000);
$(this).html("Read less");
$(this).removeClass("servicereadmore");
$(this).addClass("servicereadless");
});
$(document).on('click', ".servicereadless" ,function() {
$('.hiddenservices').slideUp(1000);
$(this).html("Read more");
$(this).removeClass("servicereadless");
$(this).addClass("servicereadmore");
});
That currently works above but opens all the hidden text as stated, the comments are were I have been trying to only expand within the parent div of the button I pressed
Your clickable <a> tags should probably be buttons, since that's the role they're in. Also, your functions aren't working currently because you've added
return false;
as the first statement of each one. That prevents any of the code after that from ever running. Instead of that, either change those <a> links to <button type=button> or else add a parameter to the handlers ("e" or "event") and call
e.preventDefault();
in the handler.
To affect only the portion of the page relevant to the "Read More" links, you just need to navigate the DOM:
$(this).closest('.myinfo').find('.hiddenservices').slideDown(1000);
That means: "staring from the clicked element, climb up the DOM to find the closest element with class 'myinfo', and then from that point down find all the elements with class 'hiddenservices' and slide them down."
A couple of other problems: you'll need to start the "hiddenservices" sections off as hidden, or otherwise not visible somehow. Also, another issue with your jsfiddle was that you didn't have jQuery selected. That's something you could quickly learn just by checking the error console.
Here is a repaired jsfiddle.
You dont have to use that much of code for this purpose. USe simply like
$(document).on('click', ".servicereadmore", function (e) {
e.preventDefault();
if ($(this).parent().find('.hiddenservices').is(":visible")) {
$(this).html("Read more");
} else {
$(this).html("Read less");
}
$(this).parent().find('.hiddenservices').slideToggle(1000);
});
Instead of adding and removing the class name, you can just use slideToggle().
Demo

Change Div Class on click takes multiple clicks before it works

I used the methods in this question:
change div class onclick on another div, and change back on body click
So here's my jQuery function:
jQuery('.checkbox_wrapper').on('click', function(e){
jQuery(this).parent()
.toggleClass('not_selected')
.toggleClass('selected');
});
However it doesn't seem to be working properly. It takes multiple clicks before the class changes.
See my jsfiddle:
http://jsfiddle.net/7A3vw/
I cut it down to the bare essentials thinking it might be conflicting javascript, but even with the single function it takes multiple clicks before the class actually changes. Because the production environment has 1 click toggle a hidden checkbox, multiple clicks is not reasonable.
Could someone help me figure out what's causing this issue?
The click function fires twice, once for the image, and once for the input, as both will bubble to the parent element, and firing twice reverts the classes again (proof).
Just target the image instead, as that is what you're really trying to click, not the parent :
jQuery('.deck_card img').on('click', function (e) {
jQuery(this).closest('div').parent().toggleClass('not_selected selected')
});
FIDDLE
i guest you need the checkbox checked together with the toggling of your div.
$(document).ready(function(e) {
$('.checkbox_wrapper').on('click', function(e){
var checked = $(this).find('input[type="checkbox"]').is(":checked");
if(checked){
jQuery(this).parent().addClass('selected').removeClass('not_selected');
}else{
jQuery(this).parent().addClass('not_selected').removeClass('selected');
}
});
});
Your code is triggering click event twice. So use .preventDefault()
This makes the default action of the event will not be triggered.
$('.checkbox_wrapper').on('click', function(e){
$(this).parent()
.toggleClass('not_selected')
.toggleClass('selected');
e.preventDefault(); // prevent the default action to be
}); // triggered for next time
Check this JSFiddle
try this
jQuery(document).on("click",'.checkbox_wrapper', function(e){
jQuery(this).parent()
.toggleClass('not_selected')
.toggleClass('selected');
});
Multiple Clicks are getting triggered because you are using class selector. You need to use not to exclude extra elements :
jQuery("div.checkbox_wrapper :not('div.checkboxdiv')").on('click', function(e){
jQuery(this).parent()
.toggleClass('not_selected selected')
});
Here is a FIDDLE.

Input:Checked jQuery vs CSS?

Unless I am mistaken. jQuery and CSS handle the :checked selector very differently. In CSS when I use :checked, styles are applied appropriately as I click around, but in jQuery it only seems to recognize what was originally in the DOM on page-load. Am I missing something?
Here is my Fiddle
In jQuery:
$('input:checked').click(function () {
$('input:checked').css('background','#FF0000');
$('input:checked+label').css('background','#ff0000');
});
In CSS:
input:checked+label {font-weight:bold;color:#5EAF1E}
UPDATE:
I should clarify that what I am looking to do is trigger behavior if a user clicks an already selected radio button.
Try setting up the handler this way:
$('body').on('click', 'input:checked', function() {
// ...
});
The way you have it, you're finding all the elements that are checked when that code runs. The above uses event bubbling so that the test is made when each "click" happens.
Inside your handler, you're updating the style for all checked elements, even though any particular click will only change one. That's not a huge deal if the number of checkboxes isn't too big.
edit — some further thought, and a helpful followup question, makes me realize that inside an event handler for a radio button "click" event, the button will always be ":checked". The value of the "checked" property is updated by the browser before the event is dispatched. (That'll be reversed if the default action of the event is prevented.)
I think it'll be necessary to add a class or use .data() to keep track of a shadow for the "checked" property. When a button is clicked, you'd see if your own flag is set; if so, that means the button was set before being clicked. If not, you set the flag. You'll also want to clear the flag of all like-named radio buttons.
You bound the event only to the inputs that were initially checked. Remove :checked from the first selector and it works as intended (but ugly.)
http://jsfiddle.net/8rDXd/19/
$('input').click(function () {
$('input:checked').css('background','#FF0000');
$('input:checked+label').css('background','#ff0000');
});
you would of course need to "undo" the css change you made with jQuery to make it go away when the input is unchecked.
$('input').click(function () {
$('input').css('background','').filter(":checked").css('background','#FF0000');
$('input+label').css('background','');
$('input:checked+label').css('background','#ff0000');
});
http://jsfiddle.net/8rDXd/20/
AFTER UPDATE
Keep track of the status of the radio buttons. For example, use .data() to keep an in-memory state of the radio buttons.
$(function () {
var $radio = $(":radio");
$radio.filter(":checked").data("checked", true);
$radio.on("click", function () {
if ($(this).data("checked")) {
alert("Already selected");
}
$radio.data("checked", false).filter(":checked").data("checked", true);
});
});
See it live here.
BEFORE UPDATE
I think you want to use .change() here.
$('input:radio').change(function () {
$('input, input+label').css('background', '');
$('input:checked, input:checked+label').css('background', '#f00');
}).change();
See it live here.

jQuery toggle() issue

I am using a script from this discussion: https://wordpress.stackexchange.com/a/14711/14649
It works great, but when I select a different radio input, the original box doesn't toggle off (bad), but the new box does appear (good). This happens for any additional boxes I add.
jQuery is not my thing, and I have been researching around with no luck! Here is my code:
<script type='text/javascript'>
jQuery(document).ready(function($) {
$('#feature_box').hide();
$('#standard_lead').hide();
// one box
$('#value_feature_box').is(':checked') ? $("#feature_box").show() : $("#feature_box").hide();
$('#value_feature_box').click(function() {
$("#feature_box").toggle(this.checked);
});
// second box
$('#value_standard_lead').is(':checked') ? $("#standard_lead").show() : $("#standard_lead").hide();
$('#value_standard_lead').click(function() {
$("#standard_lead").toggle(this.checked);
});
});
</script>
Thanks for taking a look!
The reason why the other box doesn't disappear is because you didn't tell it to!
$('#value_feature_box').click(function() {
$("#feature_box").toggle(this.checked);
});
This says to toggle the visibility of #feature_box, when you click on #value_feature_box. If #value_feature_box is not a checkbox, then change the inner code to $("#feature_box").toggle();. If you want something to disappear as well, then tell it to:
$('#value_feature_box').click(function() {
$("#feature_box").toggle();
$("#standard_lead").toggle();
});
The value on the inside of the toggle() parentheses is telling it to either appear or disappear(true or false).
You are toggling only one box on click - you need to toggle both, see this jsFiddle:
http://jsfiddle.net/Gr8Jq/
With this (and similar for the other box):
$('#value_feature_box').click(function() {
$("#feature_box").toggle(this.checked);
});
you are basically saying - when clicked (so this.checked will always be true), toggle the element. From the docs:
http://api.jquery.com/toggle/
you are using the version of toggle that has showOrHide parameter and always passing true, so always showing and only the box that was clicked on.

Categories

Resources