Declaring more than one button in jQuery - javascript

I am trying to make a webpage that has 2 buttons performing different actions. WHen i click on one button, it is performing both the functions but i want it to perform just one function.
TASK 3.1: 200x200 green box div:
<button>Remove</button>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").remove();
});
});
<br/>
</script>
<button>Animate</button>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({ left:'300px' });
});
});
</script>
<div style="
width: 200px;
height: 200px;
padding: 25px;
border: 25px solid green;
margin: 25px;
position: absolute;">
</div>

The selector "button" matches every button in the document at that time. When a selector matches multiple elements, the $.fn.click method actually loops over that resulting collection and binds to each and every element matched.
If you'd like to match only particular elements, you'll need to distinguish them from other matched elements. One of the most common ways to do this if by giving them a unique ID:
<button id="remove">Remove</button>
<button id="animate">Animate</button>
And then target those specifically from your scripting:
$("#remove").click(function remove () {
$("div").remove(); // This removes every div from the document
});
$("#animate").click(function animate () {
$("div").animate({ left: 300 }); // Animates the left property of every div
});

You need to assign a different id or class to each button. You can also condense both scripts into one. Also, seems that instead of using a div selector, you should also assign a specific id or class to the divs.
<script>
$(document).ready(function(){
$("#button1").click(function(){
$("div").remove();
});
$("#button2").click(function(){
$("div").animate({
left:'300px'
});
});
});
</script>

<button id="bremove"> Remove</button>
<script>
$(document).ready(function(){
$("button#bremove").click(function(){
$("div").remove();
});
});
<br/>
</script>
<button id="banimate"> Animate</button>
<script>
$(document).ready(function(){
$("button#banimate").click(function(){
$("div").animate({
left:'300px'
});
});
});
</script>

Related

Trigger each div independently using same script

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()
}
}
);
});

jquery slideToggle opens all divs instead of just the div that is required

I have a page that can have a variable number of <div> the idea is people can click the + symbol which is an <img> then the div that is linked to the img tag will display.
I currently have:
PHP/HTML
$plus = '<img src="images/plus.png" class="clickme" width="20px" height="20px">';
$table .= '<div>'.$plus.'</div>';
$hidden .= '<div class"diary">-Content-</div>';
JS
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$( ".clickme" ).click(function() {
$( ".diary" ).slideToggle( "slow", function() {
});
});
});
</script>
This obviously opens all divs and not just the one that is clicked on. I have looked at other similar questions on here and have tried a number of variations such as:
$(document).ready(function(){
$(".clickme").click(function(){
$(this).next(".diary").toggle();
});
});
However, when I try these it just stops working altogether. i.e. none of the divs slide up or down. I see the examples work on JS Fiddle but as soon as i apply it to my page I get nothing.
I am possibly doing something really dumb for it not to work but can't see what.
thanks for any help.
The HTML output should look like
<div>
<div>
<table>
<img class="clickme">
</table>
</div>
<div class="diary">
<table> content </table>
</div>
<div>
(based on tht HTML provided)
Best way would be to add an attribute with matching indexes to both elements
<div>test toggle
<div class="clickme" data-index="1">click me</div>
<div class="toggle" id="obj_1">toggled field</div>
</div>
and then in the JQuery:
$(function () {
$(".clickme").click(function () {
//get number from clicked element's attribute
var index =$(this).attr('data-index');
//select element with id that matches index and toggle
$('#obj_'+index).toggle();
});
})
After looking at your code, i can see that the slideToggle call is maded on .diary class which is probably applied on each of your elements.
I suggest you to put your diary div inside the $plus div then use jquery children or simply give your .diary divs a unique id and use the id attribute for your
toggle.
EDIT:
Here is a simple html output:
<div class="clickme">
<div class="diary">CONTENT HERE</div>
</div>
Add this in the CSS:
.clickme {
background: url('images/plus.png') no-repeat top left;
min-width: 20px;
min-height: 20px;
cursor: pointer;
}
Script tag:
<script>
$(function() {
$(".clickme").click(function() {
$(this).children().slideToggle("slow");
});
});
</script>
Note that i'd let the diary class for your usage and styling purpose but it's not used anywhere.

JQuery event dosen't work after .addClass

Why the div#1 dosen't change text. What i'm doing wrong?
<div id="1" class="a" style="width: 300px;height: 300px; background-color: #003366"></div>
<div id="2" class="b" style="width: 300px;height: 300px; background-color: #003366"></div>
<script>
$(document).ready(function(){
$(".b").click(function(){
$(this).text("hello");
});
$(".a").mouseover(function(){
$(this).addClass("b");
});
});
</script>
Event handlers are added to the elements that match the selector at that time, changing the selector later does not magically make the event handler work.
You could use delegated event handlers for this
$(document).ready(function(){
$(document).on("click", ".b", function(){
$(this).text("hello");
});
$(".a").mouseover(function(){
$(this).addClass("b");
});
});
But why are you doing this, it seems like a strange pattern to activate a click handler only after the same element has been hovered, as you couldn't possibly click it unless the mouse is over it ?
Try this
$("body")
.on('click', '.a', function (){
$(this).addClass("b");
})
.on('click', '.b', function (){
$(this).text("hello");
})

How to show the child div on mouse hover of parent div

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);
});
});
});

Onclick change div style + onclick outside div remove style change

I would like to change the style on a div with an onclick... and remove the style when clicking somewhere outside of the div.
I have the following code setup... can someone help me to remove the style on the divs if you click anywhere else on the page?
<head>
<style type="text/css">
.account{
width: 100px;
height: 100px;
border: 1px solid #000;
}
.selected{
border: 2px solid #F00;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(".account").click(function(){
$(".selected").removeClass("selected");
$(this).addClass("selected");
});
});
</script>
</head>
<body>
<h1>the test</h1>
<div class="account">test 1</div>
<div class="account">test 2</div>
</body>
Thank you very much for any help you can give me!!!
The following should do it:
$(document).on('click', function(e) {
if($(e.target).hasClass('account')) {
// do style change
}
else {
// undo style change
}
});
It binds the event handler to the entire document, so you'd have problems with any event handlers on more specific elements that call e.stopPropagation().
Try this.
$(document).ready(function(){
$(".account").click(function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
//This event handler will take care of removing the class if you click anywhere else
$(document).click(function(){
$(".selected").removeClass("selected");
});
});
Working demo - http://jsfiddle.net/yLhsC/
Note that you can use on or delegate to handle click event on account elements if there are many on the page.
Something like this.
Using on if using jQuery 1.7+
$('parentElementContainingAllAccounts').on('click', '.account', function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
Using delegate
$('parentElementContainingAllAccounts').delegate('.account', 'click', function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
You can achieve this behavior with attaching click listener on body element e.g.:
$("body").click(function(){
});
Try this:
$(document).ready(function() {
$('.account').click(function(e) {
e.stopPropagation();
$(this).addClass("selected");
});
$(document).click(function(){
$('.selected').removeClass('selected');
});
});

Categories

Resources