Is there a way to put multiple classes in one code?
I have many of those ".dwlnd-trg" classes. Like ".dwlnd-trg2", ".dwlnd-trg3" ".dwlnd-trg4" and ".dwlnd", ".dwlnd2", ".dwlnd3", ".dwlnd4" and so on.
Only ".s-dwlnd" stays always the same because this is the class which displays an animated svg image.
At the moment i have copied and pasted a working code in my website's head and it's great but would it be much cleaner if it's not 4, 6 or soon 8 instead of one good looking code? :) I tried to but without success...
here's the code looking so far:
$( document ).ready(function() {
$( ".dwlnd-trg" ).click(function() {
$( ".dwlnd" ).addClass( "s-dwlnd" );
setTimeout(function() {
$(".dwlnd").removeClass("s-dwlnd");
}, 3000); // Delay of 3 seconds
});});
$( document ).ready(function() {
$( ".dwlnd-trg2" ).click(function() {
$( ".dwlnd2" ).addClass( "s-dwlnd" );
setTimeout(function() {
$(".dwlnd2").removeClass("s-dwlnd");
}, 3000); // Delay of 3 seconds
});});
$( document ).ready(function() {
$( ".dwlnd-trg3" ).click(function() {
$( ".dwlnd3" ).addClass( "s-dwlnd" );
setTimeout(function() {
$(".dwlnd3").removeClass("s-dwlnd");
}, 3000); // Delay of 3 seconds
});});
$( document ).ready(function() {
$( ".dwlnd-trg4" ).click(function() {
$( ".dwlnd4" ).addClass( "s-dwlnd" );
setTimeout(function() {
$(".dwlnd4").removeClass("s-dwlnd");
}, 3000); // Delay of 3 seconds
});});
In my opinion, this is a cleaner solution.
Besides the fact that your function becomes concise, easy to understand and maintain and you don't have to update it to add new items, on the markup side it separates the meaning of class (as a style anchor) from what it's working as a selector for the function.
I can't know your context but, If you also don't need different classes for the target div, you can also use attributes to set the right target.
$( document ).ready(function() {
$(".dwlnd-trg").click(function() {
// save the target reference via ref attribute
var intref = $( this ).attr( 'ref' );
// pass the target reference to get the right one
$( ".dwlnd"+intref ).addClass( "s-dwlnd" );
setTimeout(function() {
$( ".dwlnd"+intref ).removeClass("s-dwlnd");
}, 3000); // Delay of 3 seconds
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<style>
.s-dwlnd { border: solid 1px #ccc; color:red;}
</style>
<!--use ref attribute as a target reference -->
<div class="dwlnd-trg" ref="1">click me! (1)</div>
<div class="dwlnd-trg" ref="2">click me! (2)</div>
<div class="dwlnd1">animate me! 1</div>
<div class="dwlnd2">animate me! 2</div>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
</body>
</html>
If you can do it based on id it makes it a lot easier because you can't have multiple id's. But you can have multiple classes. Here is an example with id.
$(document).ready(function() {
$("#dwlnd-trg, #dwlnd-trg2, #dwlnd-trg3, #dwlnd-trg11, #dwlnd-trghahaha").click(function() {
//get the id of the trigger element that is clicked
var thisId = $(this).attr("id");
//get everything after "dwlnd-trg" form the id.
var idStripped = thisId.replace('dwlnd-trg','');
//Use the found id addition in the selector
$(".dwlnd" + idStripped).addClass("s-dwlnd");
setTimeout(function() {
$(".dwlnd" + idStripped).removeClass("s-dwlnd");
}, 3000); // Delay of 3 seconds
});
});
.s-dwlnd {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="dwlnd-trg">dwlnd-trg</button>
<button id="dwlnd-trg2">dwlnd-trg2</button>
<button id="dwlnd-trg3">dwlnd-trg3</button>
<button id="dwlnd-trg11">dwlnd-trg11</button>
<button id="dwlnd-trghahaha">dwlnd-trghahaha</button>
<div class="dwlnd">dwlnd</div>
<div class="dwlnd2">dwlnd2</div>
<div class="dwlnd3">dwlnd3</div>
<div class="dwlnd11">dwlnd11</div>
<div class="dwlndhahaha">dwlndhahaha</div>
To put multiple class, you to try something like :
$( ".dwlnd-trg, .dwlnd-trg2, .dwlnd-trg2" )
Good luck!
You can use a selector like this:
$('[class^="dwlnd-trg"]') //Select every element that has a class attribute starting with "dwlnd-trg".
or
$('[class˜="dwlnd-trg"]') //Select every element that has a class attribute containing "dwlnd-trg".
But beware the performance issue (since selecting from class is a much faster approach)
You can use attribute starts with selector:
$( '[class^="dwlnd-trg"]' ).click(function() {
var n = this.className.match(/\d+$/)[0] // grab the number
$( ".dwlnd" + n ).addClass( "s-dwlnd" );
setTimeout(function() {
$( ".dwlnd" + n ).removeClass("s-dwlnd");
}, 3000); // Delay of 3 seconds
});
First of all, you only need one $(document).ready. Just place all code in one block.
Second, you can create a function that takes the class of the selector as parameter.
Example:
$( document ).ready(function() {
// Put all handlers here
$( ".dwlnd-trg4" ).click(function() {
addclass(dwlnd4);
});
$( ".dwlnd-trg3" ).click(function() {
addclass(dwlnd3);
});
});
function addClass(class){
("." + class ).addClass( "s-dwlnd" );
setTimeout(function() {
$("." + class).removeClass("s-dwlnd");
}, 3000); // Delay of 3 seconds
}
But if you really want to best function, I would suggest adding a date-attribute to the html. And work with an e.target so you would know which element has been clicked. But maybe this refactor is too big for you. I could add an example of this if you are interested.
Related
<div class="circle done">
<span class="label">1</span>
my code is above
I want to change 1 into a tick if div has "done" class
How do I do that ?
$(document).ready(function() {
$(".done span.label").html("your tick html");
});
Use this on your body tag:
<body onLoad="tick()">
And add this in your javascript
function tick(){
var labeltext = $('.label').val();
if (labeltext == "1"){
$('.done').text("✓");
}else{}
};
$( document ).ready(function() {
console.log( "ready!" );
const el = $(".circle");
if (el.hasClass('done')) {
$( "span.label" ).html('done');
}
});
This is done with jQuery, you first wait for the DOM to load, once it has. Then check if 'done' class is applied to the element if it is then change content of the span tag.
This should do it...
$(document).ready(function (){
$(".done").next("span").html("✔");
}
);
I was working on my code and wanting to figure out how i can store draggable objects into an array because I am creating a math game that will recognize the draggable element and determine whether the problem is correct which is addition here is my code
<script>
$(function() {
$( "#draggable1" ).draggable();
});
</script>
<script>
$(function() {
$( "#draggable2" ).draggable();
});
</script>
<script>
$(function() {
$( "#draggable3" ).draggable();
});
</script>
<script>
$(function() {
$( "#draggable4" ).draggable();
});
</script>
<script>
$(function() {
$( "#draggable5" ).draggable();
});
</script>
<script>
$(function() {
$( "#draggable6" ).draggable();
});
</script>
<script>
$(function() {
$( "#draggable7" ).draggable();
});
</script>
<script>
$(function() {
$( "#draggable8" ).draggable();
});
</script>
and then i am trying to put these draggable elements into an array
<div data-role="main" class="ui-content">
<script>
var theimagestwo = new Array();
theimagestwo[1] = "#draggable1";
theimagestwo[2] = "#draggable2";
document.getElementById("pagethree").innerHTML = theimagestwo[1];
</script>
what am i doing wrong? they are just coming up as text
Take a look at this part of your code (I added comments):
// Create a new array
var theimagestwo = new Array();
// Push the strings "#draggable1" and "#draggable2" into the array
theimagestwo[1] = "#draggable1";
theimagestwo[2] = "#draggable2";
// Set inner HTML as theimagestwo[1] (which is "#draggable1")
document.getElementById("pagethree").innerHTML = theimagestwo[1];
So, as you say, the result is "coming up as text" because it is text.
If I understand you correctly you want the contents of #pagethree to be the element #draggable1 (and not the string "#draggable1"). So you should replace the code above with:
var theimagestwo = new Array();
theimagestwo[1] = $("#draggable1");
theimagestwo[2] = $("#draggable2");
$("#pagethree").empty().append(theimagestwo[1]);
you can create a function for that and loop through using .each()
$('[id^="draggable"]').each(function(){ // [id^="draggable"] mean select all elements there ids starts with draggable
makeItDraggaple($(this));
});
function makeItDraggaple(el){
el.draggable();
$("#pagethree").append(el);
}
Working Demo
or you can use just use .each() without need a function
$('[id^="draggable"]').each(function(){ // [id^="draggable"] mean select all elements there ids starts with draggable
$(this).draggable();
$("#pagethree").append($(this));
});
Demo
On top of the answer from #Mohamed-Yousef, if you're looking to place all these elements in the "pagethree" container, you can probably do that by adding one line:
$('[id^="draggable"]').each(function(){
makeItDraggaple($(this));
$(this).appendTo("#pagethree");
});
There are some inefficiencies in doing $(this) twice and likely in not caching $("#pagethree") somewhere. But it's an (untested!) start.
I want to change the ID of an element (a <div>) using jQuery. Below is an example of my JavaScript, CSS and HTML. Right now, when I click the <div>, nothing happens.
$( ".pre_div" ).click(function() {
$( ".pre_div" ).attr('id','after_div');
});
$( ".after_div" ).click(function() {
$( ".after_div" ).attr('id','pre_div');
});
#pre_div {width:20px;height:20px;background-color:red;cursor:pointer;}
#after_div{width:20px;height:20px;background-color:blue;cursor:pointer;}
<div id="pre_div">:-)</div>
. is for classes and # is for ids, plus you have to use the .on() function, otherwise it will not work
$(document).on('click','#pre_div',function() {
$(this).attr('id','after_div');
});
$(document).on('click','#after_div',function() {
$(this).attr('id','pre_div');
});
JSFIDDLE DEMO
You should use # – id selector – instead of . – class selector (also, you can use this to access element within it's event listener):
$( "#pre_div" ).click(function() {
$(this).attr('id','after_div');
});
$( "#after_div" ).click(function() {
$(this).attr('id','pre_div');
});
JSFiddle
Please use $(this) to refer to the clicked item otherwise you may give many item the same id. However, with this approach, you are still assiging the same id to each clicked div, which is not good. How about adding the index of the clicked div to make it a unique id:
$(".pre_div").click(function() { //any div with pre_div class
$(this).attr('id'+ $(this).index(),'after_div');
});
$(".after_div").click(function() { //any div with after_div class
$(this).attr('id'+ $(this).index(),'pre_div');
});
"pre_div" and "after_div" are not classes, they are id's of your div
Should access it like this way.
$( "#pre_div" ).click(function() {
$( "#pre_div" ).attr('id','after_div');
});
$( "#after_div" ).click(function() {
$( "#after_div" ).attr('id','pre_div');
});
My home page contains multiple boxes.
On each boxes, when mouseover in or out , the title disappears and the content appears.
It works fine.
The problem is that when mouseovering more than one box on a short period of time, it is a mess.
$( ".views-field-wrapper" ).each(function(){
$( this ).hover(function() {
$( "#front_panel",this ).fadeOut(400);
$( "#back_panel",this ).delay(500).fadeIn(1000);
}, function(){
$( "#back_panel",this ).fadeOut(400);
$( "#front_panel",this ).delay(500).fadeIn(1000);
});
});
How can I stop the previous mouseover reaction when mouseovering another box?
EDIT :
My intial code: http://jsfiddle.net/tz3d6ct6/
Kumar's code that works perfectly with jquery > 1.6 (I must use jquery1.4) http://jsfiddle.net/hrkf5p7w/
Try to use stop() and no need to use loop to bind hover event,
$( ".views-field-wrapper" ).hover(function() { // no need to use each loop
$( "#front_panel",this ).stop(true).fadeOut(400);
$( "#back_panel",this ).delay(500).fadeIn(1000);
}, function(){
$( "#back_panel",this ).stop(true).fadeOut(400);
$( "#front_panel",this ).delay(500).fadeIn(1000);
});
Try it without using using delay() like,
$(".views-field-wrapper").hover(function () { // no need to use each loop
$("#front_panel", this).stop(true).fadeOut(400);
$("#back_panel", this).fadeIn(1000);
}, function () {
$("#back_panel", this).stop(true).fadeOut(400);
$("#front_panel", this).fadeIn(1000);
});
$(".views-field-wrapper").hover(function () { // no need to use each loop
$("#front_panel", this).stop(true).fadeOut(400);
$("#back_panel", this).fadeIn(1000);
}, function () {
$("#back_panel", this).stop(true).fadeOut(400);
$("#front_panel", this).fadeIn(1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='views-field-wrapper type-t nodetype-t'>
<div id='front_panel'>title</div>
<div style='display:none' id='back_panel'>teaser</div>
</div>
General javascript question here, which would also be good to know how(if possible) to do in jquery.
Can you trigger a click event when hovering over an item?
I know there will be people asking why, but please just humour me.
Many thanks,
C
Take a look at the trigger function:
$(someElement).trigger('click');
Just use click()
$(selector).click();
Or, alternatively just move your click() code out into a common function and call that from hover().
Quite simply:
$(selector).mouseenter(function() { $(this).click() });
$('myselector').hover(function(){
$(this).trigger('click');
});
EDIT: way later than the post but just to illustrate how to both add the handler AND trigger it.
$('myselector').on('click',function(){
// handle click event, put money in my bank account
}).on('mouseenter',function(){
$(this).trigger('click'); // only on enter here
// handle hover mouse enter of hover event, put money in my bank account
}).on('mouseleave',function(){
// handle mouse leave event of hover, put money in my bank account
}).trigger('click');
Just need it one time?
$('myselector').on('click',function(){
// handle click event, put money in my bank account
}).one('mouseenter',function(){
$(this).trigger('click'); // only on enter here once
// handle hover mouse enter of hover event, put money in my bank account
}).on('mouseenter',function(){
// handle hover mouse enter of hover event, put money in my bank account
}).on('mouseleave',function(){
// handle mouse leave event of hover, put money in my bank account
});
jQuery can trigger 'click' all object except tag a
let's try this code on console
and see what happen on this page
$('a').bind('mouseover', function(){
$(this).trigger('click');
console.log('hover'); // let me know when it hovering <a>
});
$('#selector').bind('mouseover',function(){
/*DO WHAT YOU WANT HERE*/
});
that should do the trick
It is possible to trigger a click event on hover.
Try the following example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hover + (mouseup/mousedown, click) demo</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p class="up">Press mouse and release here.</p>
<p class="hover1">Press mouse and release here. HOVER+UP/DOWN</p>
<p class="hover2">Press mouse and release here. HOVER.UP/DOWN</p>
<p class="hover3">Press mouse and release here. HOVER.CLICK</p>
<script>
$( "p.up" )
.mouseup(function() {
$( this ).append( "<span style='color:#f00;'>Mouse up.</span>" );
})
.mousedown(function() {
$( this ).append( "<span style='color:#00f;'>Mouse down.</span>" );
});
$( "p.hover1" )
.hover(
function() {
$( this ).append( "<span style='color:#f00;'>Hover IN.</span>" );
},
function() {
$( this ).append( "<span style='color:#00f;'>Homer OUT.</span>" );
})
.mouseup(function() {
$( this ).append( "<span style='color:#f00;'>Mouse up.</span>" );
})
.mousedown(function() {
$( this ).append( "<span style='color:#00f;'>Mouse down.</span>" );
});
$( "p.hover2" )
.hover(
function() {
$( this ).append( "<span style='color:#f00;'>Hover IN.</span>" );
},
function() {
$( this ).append( "<span style='color:#00f;'>Homer OUT.</span>" );
});
$( "p.hover2" )
.mouseup(function() {
$( this ).append( "<span style='color:#f00;'>Mouse up.</span>" );
})
.mousedown(function() {
$( this ).append( "<span style='color:#00f;'>Mouse down.</span>" );
});
$( "p.hover3" )
.hover(
function() {
$( this ).append( "<span style='color:#f00;'>Hover IN.</span>" );
},
function() {
$( this ).append( "<span style='color:#00f;'>Homer OUT.</span>" );
});
$( "p.hover3" )
.click(function() {
$( this ).append( "<span style='color:#00f;'>CLICK.</span>" );
});
</script>
</body>
</html>
You might want to also add a delay on hover so that it won't immediately trigger. Delay will be useful if you are going to use it in a list of thumbnails.
var hoverTimer;
var hoverDelay = 200;
$('.classSelector').hover(function() {
var $target = $(this);
// on mouse in, start a timeout
hoverTimer = setTimeout(function() {
// do your stuff here
$target.trigger('click');
}, hoverDelay);
}, function() {
// on mouse out, cancel the timer
clearTimeout(hoverTimer);
});