I'm trying to get each blue div (<div id="rectangle"></div>) to fire independently.
Right now, if you hover/click over the first one, both fire simultaneously, and if you hover/click over the second one, neither fires.
This is a common question and has been addressed elsewhere, but I've tried to implement several different versions and apply it to this particular code, and it's not working. I was hoping someone could provide some explanation to help me learn, and I can compare to the other posts I've tried out to understand what the difference is.
$('.rectangle1').hide();
$('#rectangle').on('click', function() {
clicked = !clicked;
});
$('#rectangle').hover(function() {
$('.rectangle1').slideDown()
},function() {
if (!clicked) {
$('.rectangle1').slideUp()
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rectangle"></div>
<div class="rectangle1"></div>
<div id="rectangle"></div>
<div class="rectangle1"></div>
http://jsfiddle.net/Q5cRU/99/
One problem is that you're using id="rectangle" for two elements. According to MDN:
The id global attribute defines a unique identifier (ID) which must be unique in the whole document.
jQuery is only adding the event listeners to the first element with that ID.
The answer is simple: The event listener was only applied to the first #rectangle. jQuery does not select more than one #ID'd element. With that being said it is not semantic to use the same id on more than one element.
Here's what you are looking for: http://jsfiddle.net/Q5cRU/116/
$(document).ready(function() {
$('.rectangle1').hide();
$('.rectangle').data( 'clicked', false).click(function() {
$(this).data( 'clicked', !$(this).data('clicked'));
}).hover(
function() {
$(this).next('.rectangle1').slideDown();
},
function() {
if (!$(this).data('clicked')) {
$(this).next('.rectangle1').slideUp();
}
}
);
});
$("div.rectangle1").mouseover(function() {
$(this).stop(true, true).show();
});
Well in HTML, the id attribute must be unique per element. See this. The class attribute can be shared by multiple elements to have the same style effect or same purpose. So the first and second div can't have the same id - "rectangle". To fire event independently you can assign different id for them.
HTML:
<div>
<div class="rectangle"></div>
<div class="rectangle-hover"></div>
</div>
<div>
<div class="rectangle"></div>
<div class="rectangle-hover"></div>
</div>
CSS:
.rectangle {
width: 140px;
height: 80px;
background: #037CA9;
margin-bottom:10px;
}
.rectangle-hover {
width: 140px;
height: 150px;
background: red;
}
Javascript:
$(function(){
var clicked = false;
$('.rectangle-hover').hide();
$('.rectangle').hover(
function(){
$(this).parent().find('.rectangle-hover').slideDown();
},
function(){
if (!clicked) {
$('.rectangle-hover').slideUp()
}
}
);
});
Related
Things have gotten out of hand for me. What started off as the simplest solution has ballooned to the point where it is no longer manageable. I need to come up with a way to simplify a process.
Currently I have a map with pins denoting specific countries world-wide. As the mouse hovers over a pin, a hidden div appears. When you mouse over another one, the previous div disappears and a new one opens. I started with like 5 of these and it wasn't an issue but I keep getting requests for more and want to manage the script in a different way now.
$('#PH1').mouseenter(function () {
$('#BO2').hide();
$('#US2').hide();
$('#UK2').hide();
$('#CH2').hide();
$('#BZ2').hide();
$('#QC2').hide();
$('#OT2').hide();
$('#VA2').hide();
$('#RU2').hide();
$('#JT2').hide();
$('#HK2').hide();
$('#SH2').hide();
$('#BJ2').hide();
$('#XI2').hide();
$('#BE2').hide();
$('#AT2').hide();
$('#FR2').hide();
$('#MX2').hide();
$('#PH2').show();
});
$('#PH1').click(function (e) {
e.stopPropagation();
});
$('#mint').click(function () {
$('#PH2').hide();
});
In this instance div id #PH1 is the pin, when the mouse enters the div it hides all of the other div's #**2 and displays the one related to #PH1, which is #PH2
This list is repeated for each DIV. Every time I need to add a new DIV I need to make each existing list longer as well as create a new one. How can this process be made much simpler?
Thats not a right way to do this, you should use classes for this. But their is a wayaround for this all you need to is add a class add class ele1 to all #**1 and ele2 to all #**2:
then
$('.ele1').mouseenter(function () {
$(".ele2").hide();
var id = this.id;
var newId = id.substring(0,2)+"2";
$("#"+newId).show();
});
Make a loop:
var all= ['#BO2', '#US2', '#UK2', '#CH2', '#BZ2', '#QC2', '#OT2', '#VA2', '#RU2', '#JT2', '#HK2', '#SH2', '#BJ2', '#XI2' , '#BE2', '#AT2', '#FR2', '#MX2', '#PH2']
all.forEach(function (i){
$(i).hide();
});
Use a class selector on all of the DIVs you want to hide/show instead of an ID.
First, add a shared class to all DIVs so we target all of them by class.
HTML: class="hidden-divs"
jQuery: $('.hidden-divs').hide();
Then show the relevant DIV.
$('#PH2').show();
Using your first example, it would look like this:
$('#PH1').mouseenter(function () {
$('.hidden-divs').hide();
$('#PH2').show();
});
You can use jquery to hide multiple divs if you can select them. For example, suppose you have a common class ".map_divs" on all your divs, you could easily do:
$(".map_divs").hide();
On a side-note, you could solve all this on CSS, using :hover. For example:
.map_divs:hover {
display: block;
}
If you can edit the div's yourself (if it is not generated by a library) I would do it like this.
Add a common class to all your divs. Then on each div, add a data attribtue to the related id.
<div class="pin" id="PH1" data-rel="PH2"></div>
Then you can have a simple function like this:
$(".pin").mouseenter(function() {
var relatedId = $(this).data("rel");
$(".pin[id$='2']").hide(); // Hide all pins with id ending in 2
$("#" + relatedId).show() //show PH2
})
Using classes might be a better option here. You can then just attach the mouseenter event on document ready to all pins. This will work for an infinite number of pins too.
$('.pin').mouseenter(function () {
$('.popup').removeClass('show');
var id = this.id.split('_')[1];
$('#popup_' + id).addClass('show');
});
.pin {
width:30px;
height:30px;
margin-bottom:20px;
background-color:red;
}
.popup {
display:none;
width:100px;
height:100px;
margin-bottom:20px;
background-color:blue;
}
.popup.show {
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pin_1" class="pin"></div>
<div id="popup_1" class="popup"></div>
<div id="pin_2" class="pin"></div>
<div id="popup_2" class="popup"></div>
If your div element is ordered like below, you can get the same result using css only, which will increase speed and overall experience (especially on phones and tablets).
When "hover" the yellow squares, the popup will be visibible even when "hover" the popup.
.pin {
width:30px;
height:30px;
margin-bottom:20px;
background-color:red;
}
.popup {
display:none;
width:100px;
height:100px;
margin-bottom:20px;
background-color:blue;
}
.pin:hover + .popup {
display:block;
}
.pin.type2 {
background-color:yellow;
}
.pin.type2:hover .popup {
display: inline-block;
margin-top: 30px;
}
<div id="pin_1" class="pin"></div>
<div id="popup_1" class="popup"></div>
<div id="pin_2" class="pin"></div>
<div id="popup_2" class="popup"></div>
<div id="pin_3" class="pin type2"><div id="popup_3" class="popup"></div></div>
<div id="pin_4" class="pin type2"><div id="popup_4" class="popup"></div></div>
I have a trigger element and a responding element.
<div class="more"></div>
<div class="info"></div>
I would like to bind an open/close type event.
$('.more').delegate($('.more'), 'click', function(){
$(this).removeClass('more');
$(this).addClass('less');
$(this).text("less...");
$('.info').addClass("open");
});
$('.less').delegate($('.less'), 'click', function(){
$(this).addClass('more');
$(this).removeClass('less');
$(this).text("more...");
$('.info').removeClass("open");
});
It doesn't work as intended, if the second function is nested in the first then you can open and close only once.
If the script is formatted sensibly as above it will open but not close.
Could anyone help me out?
Bonus if the script could support the .info could be either a sibling or the element immediately following $(.more/.less)'s parent.
I've been toying with .on/.live/.bind but less successfully than above.
Use event delegation ,and binded to document or immediate parent,not same element
$(document).on( 'click',".more", function(){
$(this).removeClass('more');
$(this).addClass('less');
$(this).text("less...");
$('.info').addClass("open");
});
$(document).on('click',".less", function(){
$(this).addClass('more');
$(this).removeClass('less');
$(this).text("more...");
$('.info').removeClass("open");
});
DEMO
NOTE: delegate was outdated with latest version of jquery ,so use on instead,
ISSUE: you are delegated with same element $('.less'),$('.more') use immediate parent or document
Just use JavaScript to toggle a class, and let CSS magic do the rest. Here is a demo: http://jsfiddle.net/pomeh/69sX5/1/
And here is the code:
HTML
<div>
Some visible content
</div>
<div class="content-fold">
<div class="more">More...</div>
<div class="less">Less...</div>
</div>
<div class="info">Some hidden additional content</div>
CSS
/* Additional content and Less button hidden by default */
.content-fold + .info, .content-fold .less {
display: none;
}
/* Additional content and Less button shown when class shown is active */
.content-fold.shown + .info, .content-fold.shown .less {
display: block;
}
/* More button hidden when additional content is shown */
.content-fold.shown .more {
display: none;
}
/*
You can also move the "div.info" into the "div.content-fold",
and use ".content-fold.shown > .info" instead of ".content-fold.shown + .info"
Browser support is quite good for adjacent selector (see http://www.quirksmode.org/css/selectors/#t11 and https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors#Browser_compatibility)
*/
JavaScript
$('.content-fold').on('click', function(){
$(this).toggleClass('shown');
});
Use id to do your task. it's easy.
Html
<div class="more" id="toggle"></div>
<div class="info"></div>
Jquery
$('#toggle').click(function(){
var $this = $(this) //store object
if($this.hasClass('more')) {
$this.removeClass('more').addClass('less').text('Less...')
$this.next('.info').addClass('open');
} else {
$this.removeClass('less').addClass('more').text('More...')
$this.next('.info').removeClass('open');
}
});
js Fiddle: http://jsfiddle.net/5N6TL/53/
I am making a personal website. I want to make it so that cliking the background changes the theme from dark to light and vice/versa. It works, but I dont want it to switch the theme if the user clicks on text, only the background of the webpage For example, if I click the text at the bottom it changes the css, but it should only do that if you click the white background.
Here is my code (Mainly checkout js/main.js, the switchTheme function and the index.html) and the website itself.
You are targeting your container class. Anytime that div (or anything in it) gets clicked, that event will fire. Try stopping the event propagation on your click event if $('this').selector === 'p' or whatever class you're using.
Also - not bad for 13 boss!
$( document ).click(function( event ) {
// if statement here
event.stopPropagation();
// else the regular behavior
});
Thanks everyone for your help! I'd almost given up and wanted to use a button to toggle it instead. The more you know!
And since this is an answer to my question: e.stopPropogation()
You can also do something like this:
document.querySelector('div').addEventListener('click', (e) => console.log("Heeeeyyy! Hoooo!"))
<div style="position: fixed; background-color: lightcoral; width: 500px; height: 180px;">
</div>
<div style="position: fixed; background-color: lightblue; width: 300px; height: 100px;">
<p>You can not click through me!</p>
</div>
Don't put the elements inside the "parent".
Move them together only by style.
How about
$("#container").on("click", "div", function(event){
event.stopPropagation();
switchTheme();
});
Add a test to see if the ID of the clicked element was actually the container.
function switchTheme( event ) {
if ( event.target.id === 'container' ) { //the container was clicked, and not a text node
if (dark) {
$("#container").css("background-color", "rgba(255,255,255,0.7);");
$("#container").css("color", "black");
dark = false;
} else {
$("#container").css("background-color", "rgba(0,0,0,0.7);");
$("#container").css("color", "white");
dark = true;
}
}
}
Try setting the following:
$("#container").on("click", "div", function(e){
e.stopPropagation();
});
I am using bootstrap theme called: Core Admin
http://wrapbootstrap.com/preview/WB0135486
This is the code I write:
<div class="span6">
<input type="checkbox" class="icheck" id="Checkbox1" name="userAccessNeeded">
<label for="icheck1">Needed</label>
</div>
And bootstrap generates me this code:
<div class="span6">
<div class="icheckbox_flat-aero" style="position: relative;">
<input type="checkbox" class="icheck" id="Checkbox7" name="userAccessNeeded" style="position: absolute; opacity: 0;">
<ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background-color: rgb(255, 255, 255); border: 0px; opacity: 0; background-position: initial initial; background-repeat: initial initial;"></ins>
</div>
<label for="icheck1" class="">Needed</label>
This is the result:
So basically it makes a pretty checkbox for me. Each time I click on the checkbox, it will add a checked class to the div:
<div class="icheckbox_flat-aero checked" style="position: relative;">
So at first I wanted to listen the input field being changed like this
$('input[type="checkbox"][name="userAccessNeeded"]').change(function () {
if (this.checked) {
}
});
But it doesn't actually change the input field, but rather changes the class of <div> element.
How could I listen to checkbox being checked?
$('input#Checkbox1').change(function () {
if ($('input#Checkbox1').is(':checked')) {
$('input#Checkbox1').addClass('checked');
} else {
$('input#Checkbox1').removeClass('checked');
}
});
i solve it that way.
The template looks to be using https://github.com/fronteed/iCheck/, which has callbacks:
$('input[type="checkbox"][name="userAccessNeeded"]').on('ifChecked', function(event){
alert(event.type + ' callback');
});
Or there is also:
$('input[type="checkbox"][name="userAccessNeeded"]').iCheck('check', function(){
alert('Well done, Sir');
});
Which should work with a whole range of methods:
// change input's state to 'checked'
$('input').iCheck('check');
// remove 'checked' state
$('input').iCheck('uncheck');
// toggle 'checked' state
$('input').iCheck('toggle');
// change input's state to 'disabled'
$('input').iCheck('disable');
// remove 'disabled' state
$('input').iCheck('enable');
// change input's state to 'indeterminate'
$('input').iCheck('indeterminate');
// remove 'indeterminate' state
$('input').iCheck('determinate');
// apply input changes, which were done outside the plugin
$('input').iCheck('update');
// remove all traces of iCheck
$('input').iCheck('destroy');
Link to the Documentation: http://fronteed.com/iCheck/
You need to bind to the ifchecked event via
Use on() method to bind them to inputs:
$('input').on('ifChecked', function(event){
alert(event.type + ' callback');
});
this will change the checked state
$('input').iCheck('check'); — change input's state to checked
This worked for me
jQuery('input.icheck').on('ifChanged', function (event) {
if ($(this).prop('checked')) {
alert('checked');
} else {
alert('unchecked');
}
});
Finally solved it like this, since I am clicking on a div element, then I must listen click event of that, and then check if the div has class and what is the id of checkbox.
$('.iCheck-helper').click(function () {
var parent = $(this).parent().get(0);
var checkboxId = parent .getElementsByTagName('input')[0].id;
alert(checkboxId);
});
Just my five cents, if anyone would have the same problem..
I needed the exact checkbox states. Toggle not worked here. This one has done the required state delivery for me:
$('.iCheck-helper').click(function () {
var checkbox = $(this).parent();
if (checkbox.hasClass('checked')) {
checkbox.first().addClass('checked');
} else {
checkbox.first().removeClass('checked');
}
doWhateverAccordingToChoices();
});
#Srihari got it right except the selector. Indeed the input isn't modified onclick, but the div do :
$('.icheckbox_flat-aero').click(function(){
$(this).find('input:checkbox').toggleClass('checked'); // or .find('.icheck').
});
Hey i hope this logic should work for you
JS CODE:
$('.icheckbox_flat-aero').on('click',function(){
var checkedId=$(this,'input').attr('id');
alert(checkedId);
});
This way a general event is added for all the checkbox`s
Happy Coding :)
Looking at your question and working with bootstrap since the past 1 year, I can definitely say that the checked class being added is not done by bootstrap. Neither is the checked class being added is a property which is built into BS 2.3.*.
Yet for your specific question try the following code.
$('.icheck').click(function(){
$(this).toggleClass('checked');
});
You can get a working example here.
Update 1:
The Checkbox cannot be styled by color using CSS. Hence, the developer is using insert tag to delete the Checkbox and put in his styling code. In effect, the CSS and JS in the specified theme do the styling by putting in the new stylized code.
Instead you can listed to the click event on the div icheckbox_flat-aero.
$('.icheckbox_flat-aero').children().on('click',function(){
alert('checked');
});
Check for the example http://jsfiddle.net/hunkyhari/CVJhe/1/
you could use this:
$('input#Checkbox1').on('ifChanged',function() {
console.log('checked right now');
});
I have a number of parent divs (.parent_div), which each contain a child div (.hotqcontent) where I output data from my database using a loop.
The following is my current markup:
<div class="content">
<div class="parent_div">
<div class="hotqcontent">
content of first div goes here...
</div>
<hr>
</div>
<div class="parent_div">
<div class="hotqcontent">
content of second div goes here...
</div>
<hr>
</div>
<div class="parent_div">
<div class="hotqcontent">
content of third div goes here...
</div>
<hr>
</div>
<div class="parent_div">
<div class="hotqcontent">
content of fourth div goes here...
</div>
<hr>
</div>
</div>
What I would like to achieve is when a user hovers / mouseovers a parent div, the contents of the child div contained within should be revealed.
To achieve this I wrote the following jQuery script but it doesn't appear to be working. It's not even showing the alert!
<script>
$(document).ready(function() {
$(function() {
$('.parent_div').hover(function() {
alert("hello");
$('.hotqcontent').toggle();
});
});
});
</script>
How can I modify or replace my existing code to achieve the desired output?
If you want pure CSS than you can do it like this....
In the CSS below, on initialization/page load, I am hiding child element using display: none; and then on hover of the parent element, say having a class parent_div, I use display: block; to unhide the element.
.hotqcontent {
display: none;
/* I assume you'll need display: none; on initialization */
}
.parent_div:hover .hotqcontent {
/* This selector will apply styles to hotqcontent when parent_div will be hovered */
display: block;
/* Other styles goes here */
}
Demo
Try this
$(document).ready(function() {
$('.parent_div').hover(function() {
alert("hello");
$(this).find('.hotqcontent').toggle();
});
});
Or
$(function() {
$('.parent_div').hover(function() {
alert("hello");
$(this).find('.hotqcontent').toggle();
});
});
You can use css for this,
.parent_div:hover .hotqcontent {display:block;}
This can be done with pure css (I've added a couple of bits in just to make it a bit neater for the JSFIDDLE):
.parent_div {
height: 50px;
background-color:#ff0000;
margin-top: 10px;
}
.parent_div .hotqcontent {
display: none;
}
.parent_div:hover .hotqcontent {
display:block;
}
This will ensure that your site still functions in the same way if users have Javascript disabled.
Demonstration:
http://jsfiddle.net/jezzipin/LDchj/
With .hotqcontent you are selecting every element with this class. But you want to select only the .hotqcontent element underneath the parent.
$('.hotqcontent', this).toggle();
$(document).ready(function(){
$('.parent_div').on('mouseover',function(){
$(this).children('.hotqcontent').show();
}).on('mouseout',function(){
$(this).children('.hotqcontent').hide();
});;
});
JSFIDDLE
you don't need document.ready function inside document.ready..
try this
$(function() { //<--this is shorthand for document.ready
$('.parent_div').hover(function() {
alert("hello");
$(this).find('.hotqcontent').toggle();
//or
$(this).children().toggle();
});
});
and yes your code will toggle all div with class hotqcontent..(which i think you don't need this) anyways if you want to toggle that particular div then use this reference to toggle that particular div
updated
you can use on delegated event for dynamically generated elements
$(function() { //<--this is shorthand for document.ready
$('.content').on('mouseenter','.parent_div',function() {
alert("hello");
$(this).find('.hotqcontent').toggle();
//or
$(this).children().toggle();
});
});
you can try this:
jQuery(document).ready(function() {
jQuery("div.hotqcontent").css('display','none');
jQuery("div.parent_div").each(function(){
jQuery(this).hover(function(){
jQuery(this).children("div.hotqcontent").show(200);
}, function(){
jQuery(this).children("div.hotqcontent").hide(200);
});
});
});