If hasClass help and subtracting from variables - javascript

I am trying to make it so when the '.main' is clicked, it will toggle its class to become a '.second', with this new class it will become red but the element will have already been classed as '.main' already, thus, I can still refer to it as '.main'. After that I want it to add to the 'count' variable and, if clicked again, revert back to the appearance of the '.main' class, then subtracting from the 'count' variable!
html
<div class="container">
<div id="box" class="main"></div>
<div id="box" class="main"></div>
<div id="box" class="main"></div>
<div id="box" class="main"></div>
</div>
relevent css
.main {
background: #888888;
}
.second {
background: red;
}
#box {
width: 10px;
height: 10px;
border-radius: 10px;
margin: 1% 1%;
line-height: 100px;
text-align: center;
}
And, jQuery
$(document).ready(function() {
var count = 0;
$('.main').click(function() {
$(this).toggleClass('second')
$(this).toggleClass('main')
if ($(this).hasClass('main')) {
count++;
} else if ($(this).hasClass('second')) {
count--;
}
if (count === 4) {
alert('Success')
}
});
});
So I need help because the jQuery will keep adding to the 'count' variable even if 'this' hasClass '.second'!
IF YOU THINK YOU HAVE AN ANSWER CHECK IT IN JSFIDDLE AND CLICK THE ONE BOX 4 TIMES, IF YOU GET A PROMPT THEN THE 'COUNT--;' ISN'T SUBTRACTING STILL

You may need to change these.
Remove the count variable and instead use jQuery's length.
Do not use the same value for ID.
$(document).ready(function() {
$('.main').click(function() {
$(this).toggleClass('second').toggleClass('main')
if ($('.main').length == 4)
alert('Success')
});
});
.main {
background: blue;
}
.second {
background: red;
}
#box1, #box2, #box3, #box4 {
width: 10px;
height: 10px;
border-radius: 10px;
margin: 1% 1%;
line-height: 100px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div id="box1" class="main"></div>
<div id="box2" class="main"></div>
<div id="box3" class="main"></div>
<div id="box4" class="main"></div>
</div>

You need to remove $(this).toggleClass('main') from within $('.main').click(function() { updating the code to
$('.main').click(function() {
$(this).toggleClass('second')
if ($(this).hasClass('second')) {
count++;
} else if ($(this).hasClass('main')) {
count--;
}
if (count === 4) {
alert('Success')
}
});
when you toggle the .main class it is removed and it will not fall within the click call
And you can't have multiple items with the same ID within your HTML, you can assign class if it occurs more than once. See the fiddle linked below for an example of how you can have it
jsfiddle example: http://jsfiddle.net/ks14dnL1/4/

Related

Hover on two elements using jQuery

I have two <div> elements attached to each other, I mean there is no space between them.
<div id="box1">1</div>
<div id="box2">2</div>
And I have this jQuery code:
$('#box1 , #box2').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
My problem is when I move the mouse between box1 and box2, I still get on console log "Not".
I want those divs to be considered as one element so when I move the mouse between them I don't get on console log "Not".
Thanks in advance!
I want those divs to be considered as one element
Well, quite simply, they aren't. And they can't be. That's not how HTML and CSS works.
The hover event is triggered one for each individual element bound to the event handler. And every time you leave one of those elements it will print the "not" output as per your instructions.
There is no "fix" for this in the exact way you described, but there are alternative approaches. An obvious solution is to wrap them both in an outer div and bind the hover event to that instead. Then the whole area will be considered as one element (because it literally is). Demo:
$('#boxcontainer').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
#boxcontainer {
border: solid 1px black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boxcontainer">
<div id="box1">1</div>
<div id="box2">2</div>
</div>
friend check the code below. I think it will work for you. As you have dai you have an absolute position div you must need a parent div and the parent div position must be relative. For doing that you have to add just a simple CSS code position: relative;. You also need to do some changes to your jquery code. You can just hover on the parent div and it will do your work. Hope this code will help you.
//Box 1 Demo
$('#boxParrent1').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
//Box 2 Demo
$('#boxParrent2').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
/*Main Code that are needed*/
#boxParrent1, #boxParrent2 {
position: relative;
}
/*Codes Just used to give you a demo*/
#boxParrent1, #boxParrent2{
display: flex;
margin-bottom: 50px;
border: 1px solid #000;
}
#boxParrent1{
width: 200px;
}
#boxParrent2{
width: 210px;
}
#box1, #box2, #box3, #box4{
background: tomato;
width: 100px;
height: 100px;
display: grid;
justify-content: center;
align-items: center;
font-family: Arial;
font-size: 50px;
color: #fff;
cursor: pointer;
}
#box2, #box4{
position:absolute;
top: 0;
left:100px;
background: #02dce6;
}
#box4{
left:110px;
background: #02dce6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boxParrent1">
<div id="box1">1</div>
<div id="box2">2</div>
</div>
<div id="boxParrent2">
<div id="box3">3</div>
<div id="box4">4</div>
</div>
Try to place your 2 div's in one super div
<div id="super">
<div id="box1">1</div>
<div id="box2">2</div>
</div>
$('#super').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});

Show last fadeIn div on first position

I have 10 divs which were displayed in a random time.
How can I set the last shown div on top (rank first position) each time and not in the html order of the divs?
Here is my code:
var myVar;
function showDiv(){
var random = Math.floor(Math.random() * $('.notification').length);
$('.notification').eq(random).fadeIn(200).delay(3000).fadeOut(200);
createRandomInterval();
}
function createRandomInterval(){
setTimeout(showDiv, 500+ Math.random() * 4000);
}
$(document).ready(function(){
createRandomInterval();
});
.notification {
width: 200px;
height: 50px;
background-color: yellow;
border: 1px solid rgba(0,0,0,0.2);
margin-bottom: 5px;
text-align: center;
padding-top: 20px;
display: none;/* hide initially so that fadIn() fadeOut() will work
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="notification">1</div>
<div class="notification">2</div>
<div class="notification">3</div>
<div class="notification">4</div>
<div class="notification">5</div>
<div class="notification">6</div>
<div class="notification">7</div>
<div class="notification">8</div>
<div class="notification">9</div>
<div class="notification">10</div>
Here is my fiddle: https://jsfiddle.net/gkq21ppt/3/
EDIT: Idea for a solution
A solution could be, to wrap the divs and set them column-reverse. And then add a JS-code which sets a sequential number as flex order number to every new faded in div.
But I have no idea how to do this, with my low JS skills.
So the loop could look like:
create number starting by 1 as variable
create class width name e.g. "order-[number]"
in ".order-[number]" class set css property "order" to [number]
add this class to the loop before it is faded in
remove this class after it is faded out
Or?
You can try using .prependTo()
What this will do (I think) is remove the active notification and add it back to the container, in the first position. Because of this behaviour, flexbox shouldn't be necessary.
Note this changes the HTML structure.
updated fiddle
var myVar;
function showDiv() {
var random = Math.floor(Math.random() * $('.notification').length);
$('.notification').eq(random).prependTo('.container').fadeIn(200).delay(3000).fadeOut(200);
createRandomInterval();
}
function createRandomInterval() {
setTimeout(showDiv, 500 + Math.random() * 4000);
}
$(document).ready(function() {
createRandomInterval();
});
.notification {
width: 200px;
height: 50px;
background-color: yellow;
border: 1px solid rgba(0, 0, 0, 0.2);
margin-bottom: 5px;
text-align: center;
padding-top: 20px;
display: none;
/* hide initially so that fadIn() fadeOut() will work */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="notification">1</div>
<div class="notification">2</div>
<div class="notification">3</div>
<div class="notification">4</div>
<div class="notification">5</div>
<div class="notification">6</div>
<div class="notification">7</div>
<div class="notification">8</div>
<div class="notification">9</div>
<div class="notification">10</div>
</div>

Animating Multiple Divs

The following code works, but I have a problem since I want to have multiple portfolio objects like this one. If I use the current code it would raise all of the hidden divs (.slide) with text instead of one at a time based on hover. I can't use "this" since that would just make the picture animate upward. I could give everything ids and write a lot of JavaScript code that is repetitive, but I am almost positive that isn't the best way to do things.
Basically, How would you target a div with a hover effect that causes another div to do something and still be able to reuse the code?
The HTML for this section:
<div class="col-md-6 high">
<img class="port" src="http://loremflickr.com/320/240" alt="test">
<div class="slide">
<h3>Test Portfolio</h3>
</div>
</div>
The CSS for this section:
.high {
height: 200px;
overflow: hidden;
}
.port {
width: 100%;
height: 200px;
}
.slide {
background-color: rgba(74, 170, 165, 0.7);
color: white;
position: relative;
top: -34px;
height: 200px;
width: 100%;
padding: 20px;
text-align: center;
}
The JavaScript for this section:
$(document).ready(function(){
var portfolio = {
// moves div with text over portfolio picture on hover
hoverPort: function() {
$(".port").hover(function() {
$(".slide").stop().animate({"top" : "-110px"});
}, function() {
$(".slide").stop().animate({"top" : "-34"});
});
}, // end of hoverPort function
} // end of portfolio object
portfolio.hoverPort();
}); // end of document.ready
Of course you can use this, not to animate the element itself but to refer another "closest" element based on that:
$(".port").hover(function() {
$(this).next('.slide').stop().animate({"top" : "-110px"});
}, function() {
$(this).next('.slide').stop().animate({"top" : "-34"});
});
Demo Snippet
$(".port").hover(function() {
$(this).next('.slide').stop().animate({
"top": "-110px"
});
}, function() {
$(this).next('.slide').stop().animate({
"top": "-34"
});
});
.col-md-6 {
float: left;
width: 50%;
padding:25px;
box-sizing:border-box;
}
.slide {
position: relative;
top: -60px;
color: white;
background: red;
font-size: 2em;
font-family: sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-6 high">
<img class="port" src="http://loremflickr.com/320/240" alt="test">
<div class="slide">
<h3>Test Portfolio</h3>
</div>
</div>
<div class="col-md-6 high">
<img class="port" src="http://loremflickr.com/320/240" alt="test">
<div class="slide">
<h3>Test Portfolio</h3>
</div>
</div>
You can use jQuery "eq" selector.
$(".port").eq(0).hover(function() {
$(".slide").eq(0).stop().animate({"top" : "-110px"});
});
Hovering over the first "port" will animate the first "slide".

how to make an image work as a check box?

I am working on phone-gap application in dream-weaver
I have 2 divs .pics and .cover
<div class="pics">
<div class="cover"></div>
</div>
the main idea is to change the colour of the cover div and toggle a JS variable between true and false
var checked=false;
$('.pics').click(function(){
CheckToggle();
});
function CheckToggle(){
if(checked==false){
checked=true;
$('.cover').css({"background":"rgba(255,255,255,.5)"});
}
else
checked=false;
}
I click on .pics and nothing happens
I think there is an error in the jquery code
This is what I used after all
$(function(){
$( "#item1" ).bind( "tap", PicCheck );
var checked;
var choosen="#item1";
checked=$(choosen).attr('pcheck');
function PicCheck( event ){
if(checked=="false"){
$(choosen).toggleClass("selected");
checked="true";
}
else if(checked=="true"){
$(choosen).toggleClass("selected");
checked="false";
}
$(choosen).attr('pcheck',checked);
}
});
With some css you can implement a checkbox and radio buttons with pictures. Try this :
<div>
<input id="input-1" class="img-checkbox" type="radio" name="selectTipo">
<label for="input-1" class="">
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/128px-HTML5_logo_and_wordmark.svg.png">
</label>
<input class="img-checkbox" type="radio" id="input-2" name="selectTipo">
<label for="input-2">
<img src="http://www.javatpoint.com/images/javascript/javascript_logo.png">
</label>
And in your css :
input.img-checkbox[type=radio], input.img-checkbox[type=checkbox] {
display: none;
}
img{
height:100px;
}
input.img-checkbox[type=radio]+label, input.img-checkbox[type=checkbox]+label {
border: 10px solid transparent;
display: inline-block;
border-radius: 10px;
}
input.img-checkbox[type=radio]:checked+label, input.img-checkbox[type=checkbox]:checked+label {
border: 10px solid #C6ECED;
display: inline-block;
}
See the result in the follow jsfiddle
I'd skip the Javascript and use a label element and the :checked selector.
#example {
visibility: hidden;
width: 0;
}
label {
color: purple;
}
#example:checked + label {
background-color: red;
color: white;
}
The HTML would be like this:
<input id="example" type="checkbox" name="example" value="true">
<label for="example">Example</label>
With this approach you wouldn't need to worry about tracking the checked variable and you can just figure it out normally.
Here's a demo: http://jsbin.com/cirali/1/edit?html,css,output
It is usually most convenient to use additional class for your purpose.
Here is a simple example:
var checked = false;
$('.pics').click(function() {
CheckToggle();
});
function CheckToggle() {
$('.cover').toggleClass('selected');
checked = $('.cover').hasClass('selected');
}
.cover {
background: red;
}
.cover.selected {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pics">
<div class="cover">test</div>
</div>
Edit:
Since you are using jQuery mobie, you might want to try the vclick or tap events instead of the regular click event.
Depending on how you have the elements styled, it might be better to put the action on the .cover element... If the child element .cover is the exact same height and width of the parent element .pics you wont be able to click on .pics

Moving elements between 2 div's with jQuery

I am trying to move divs between two containers (#one and #two). I can't seem to figure out how to select a div which is inside another div.
I found a similar topic about targeting class inside a div. It gave me idea of using parent.
jQuery has a large list of selectors, I assume I could use one of them. But I intuitively think I could use something like #one.draggable or some other kind of specifying path.
Example on JSFiddle
CSS:
div
{
display:inline;
background-color:#eee;
}
.draggable
{
width: 50px;
height: 50px;
background-color: lime;
z-index: 2;
display: block;
float: left;
background-color: #333333;
}
#one
{
width: 200px;
height: 200px;
background-color: #555555;
z-index: 1;
float: left;
}
#two
{
width: 200px;
height: 200px;
background-color: #777777;
z-index: 1;
float: left;
}
jQuery:
$(document).ready(function() {
$(".draggable",$(this).parent("one")).click(function () {
// move from "one" to "two"
$(this).appendTo("#two");
});
$(".draggable",$(this).parent("two")).click(function () {
// move from "two" to "one"
$(this).appendTo("#one");
});
});
HTML:
<div id="one">
<div class="draggable">1</div>
<div class="draggable">2</div>
<div class="draggable">3</div>
</div>
<div id="two">
<div class="draggable">4</div>
<div class="draggable">5</div>
<div class="draggable">6</div>
</div>
I'll try to stick to what seems to be the core of your question: use $('#one .draggable') (the space is important!) to select all divs with class 'draggable' inside the div with id 'one'.
So your full jQuery code should be:
$(document).ready(function() {
$('#one .draggable').click(function () {
// move from "one" to "two"
$(this).appendTo("#two");
});
$('#two .draggable').click(function () {
// move from "two" to "one"
$(this).appendTo("#one");
});
});
UPDATE
As you noticed, with the code above it's not possible to move the same div again after the first move. The solution is as follows:
$(document).ready(function() {
$('#one .draggable').live('click', function () {
// move from "one" to "two"
$(this).appendTo("#two");
});
$('#two .draggable').live('click', function () {
// move from "two" to "one"
$(this).appendTo("#one");
});
});

Categories

Resources