What is the best way to detect if a jQuery-selector clicked. i mean:
var elem = 'foo'
var action = $(elem ).mouseenter(function(){
$(this).css('background-image',url(elem +'.png'))
});
var elem = 'bar'
//do the same action with new elem
var elem = 'blah'
//do the same action with new elem
the problem is how can i shorten this code to one line:
$('.far').mouseenter(function(){$(this).css('background-image',url(far.png'))});
$('.foooo').mouseenter(function(){$(this).css('background-image',url(foooo.png'))});
$('.bar').mouseenter(function(){$(this).css('background-image',url(bar.png'))});
$('.some').mouseenter(function(){$(this).css('background-image',url(some.png'))});
try making this array
var arr = [ "far", "foooo", "bar", "some" ];
arr.forEach( function( item ){
$('.' + item ).mouseenter(function(){$(this).css('background-image','url('+ item +'.png'))});
//adding the click detection as well
$('.' + item ).click(function(){$(this).css('background-image','url('+ item +'.png'))});
});
$(function() {
$(document).on('mouseenter', 'div[data-background]', function() {
$(this).css({'background' : 'url('+$(this).data('background')+')',});
});
});
div {
width : 500px;
height : 320px;
border : 1px solid #A2A2A2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div data-background="https://cdn.pixabay.com/photo/2017/04/04/14/23/peacock-2201428_960_720.jpg"></div>
<div data-background="https://cdn.pixabay.com/photo/2013/07/12/18/59/peacock-154128_960_720.png"></div>
</body>
</html>
Works only in this situation.
Since you have single class selector,assuming you don't have multiple classes
$('.far','.foooo','.bar','.some').mouseenter(function(){
var selector = $(this).attr('class');
$(this).css('background-image',url(selector+'.png'));
});
You need something like this:
$(".foo").click(function (event) {
$(this).css("color", "red");
});
Again, you need click, not mouseenter. Because mouseenter is just a hover, which you could do with plain css.
Related
I have some divs and if i hover them I want an popup to show. I have six divs and six popups to show but not all at once instead only one per one.
The first function works fine but then the other do not work how can I move them all to one snippet?
<script>
document.addEventListener('DOMContentLoaded', function() {
let elements = document.querySelectorAll('#Mitarbeiter1Punkt');
let popupposts = ['647'];
elements.forEach(function(e, i) {
e.addEventListener('mouseenter', function() {
elementorProFrontend.modules.popup.showPopup({
id: popupposts[i]
});
});
e.addEventListener('mouseleave', function(event) {
jQuery('body').click();
});
});
});
document.addEventListener('DOMContentLoaded', function() {
let elements = document.querySelectorAll('#Mitarbeiter2Punkt');
let popupposts = ['656'];
elements.forEach(function(e, i) {
e.addEventListener('mouseenter', function() {
elementorProFrontend.modules.popup.showPopup({
id: popupposts[i]
});
});
e.addEventListener('mouseleave', function(event) {
jQuery('body').click();
});
});
});
</script>
An alternative option would be to make this data-driven rather code-driven - ie the data is in the HTML, not the js. And as you're using jquery already, make use of jquery.
It's unlikely this will fix the root-cause of your issue as that's not been established (still waiting for complete sample) - this is to show how to combine this into a single function that doesn't need to be changed as you add new HTML.
$(".punkt").on("mouseenter", function() {
var id = $(this).data("popup-id");
$(".popup[data-popup-id='" + id + "']").show();
});
$(".punkt").on("mouseleave", function() {
var id = $(this).data("popup-id");
$(".popup[data-popup-id='" + id + "']").hide();
});
div {
border: 1px solid rebeccapurple;
width: 50px;
height: 50px;
text-align: center;
}
.popup {
display: none;
}
<div class='punkt' data-popup-id='A'>
1
</div>
<div class='punkt' data-popup-id='B'>
2
</div>
<div class='popup' data-popup-id='A'>
A
</div>
<div class='popup' data-popup-id='B'>
B
</div>
I would use an array of objects that maps the div IDs to the popup IDs. Loop over the array and set up all the event listeners.
document.addEventListener('DOMContentLoaded', function() {
let popupMap = [{
div: '#Mitarbeiter1Punkt',
popup: 647
},
{
div: '#Mitarbeiter2Punkt',
popup: 646
}
];
popupMap.forEach(({div, popup}) => {
let e = document.querySelector(div);
e.addEventListener('mouseenter', () => elementorProFrontend.modules.popup.showPopup(popup));
e.addEventListener('mouseleave', () => jQuery('body').click());
});
});
okay so actually i figgered it out myself:
<script>
document.addEventListener('DOMContentLoaded', function() {
let elements = document.querySelectorAll( '.mitarbeiterPunkt' );
let popupposts = [ '647', '656', '660', '664', '664', '668', '672'];
elements.forEach(function(e,i){
e.addEventListener( 'mouseenter', function(){
elementorProFrontend.modules.popup.showPopup( { id: popupposts[i] } );
} );
e.addEventListener( 'mouseleave', function(event){
jQuery('body').click();
});
});
});
</script>
The following code is not working. I would like to pass "this" (which would be .dot) from the click event to the function, findTargetSlideOfDot but I'm not sure how to go about doing that. thanks
$(document).on('click', '.dot', function() {
var targetSlide = findTargetSlideOfDot;
changeSlide(targetSlide);
})
function findTargetSlideOfDot() {
// find the slide number the user wants to see
var get = $.grep(this.className.split(" "), function(v, i){
return v.indexOf('slide_') === 0;
}).join();
var targetSlide = '.' + get;
return targetSlide;
}
function changeSlide(targetSlide) {
// hide current slide and dot
$('.slide.active, .dot.active').removeClass('active');
$(targetSlide).addClass('active');
}
Here:
$(document).on('click', '.dot', function() {
var targetSlide = $(this);
changeSlide(targetSlide);
})
function changeSlide(targetSlide) {
// hide current slide and dot
//$('.slide.active, .dot.active').removeClass('active');
$(targetSlide).toggleClass('active');
}
.dot{
width: 100px; border: 1px solid black;
padding: 10px; margin: 5px;
}
.dot.active{
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dot">test</div>
Give this a shot, modify your click function like this:
$(document).on('click', '.dot', function(e) {
// e.target should refer to the element with the dot class
})
Here's a functional code pen too: http://codepen.io/csavage1994/pen/Mppxaa
You may want to pass it as a parameter an actually call that function. And the improvement shown by Colton should be applied as well:
$(document).on('click', '.dot', function(e) {
var targetSlide = findTargetSlideOfDot( e.target );
changeSlide(targetSlide);
})
function findTargetSlideOfDot( element ) {
// find the slide number the user wants to see
var get = $.grep(element.className.split(" "), function(v, i){
return v.indexOf('slide_') === 0;
}).join();
var targetSlide = '.' + get;
return targetSlide;
}
function changeSlide(targetSlide) {
// hide current slide and dot
$('.slide.active, .dot.active').removeClass('active');
$(targetSlide).addClass('active');
}
You can choose between:
$(document).on('click', '.dot', function(e) {
findTargetSlideOfDot(e.target);
});
which gives you the element that triggered the event (was clicked)
and:
$(document).on('click', '.dot', function(e) {
findTargetSlideOfDot(e.currentTarget);
});
which gives you the element that had the event listener registered.
I have a div where when you click it, it's suppose to turn invisible, and when you click on it again, it's suppose to turn visible. But something's wrong with my code. Please take a look:
<div id = "id"> Hello </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
//*****************************************************************************
function toggleOnClick($id){
$("#"+$id).click(function() {
$("#"+$id).toggle(
function () {
$(this).css({visibility: "hidden"});
},
function () {
$(this).css({visibility: "visible"});
}); //end of $("#"+$id).toggle
}); //end of $("#"+$id).click(function()
} //end of function toggleOnclick($id)
//*****************************************************************************
$(document).ready(function(){
toggleOnClick("id");
});
</script>
P.S: Got my source from the accepted answer in this link: jQuery toggle CSS?
tggle() will toggle between display property so it will not retain place for element after it hides, You need to use css() with callback and update its opacity, it will retain it's place.
Update : The click event will not fire on element with visibility: hidden so you need to use opacity:0
Callback in css() is a function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. ( Taken from http://api.jquery.com/css/#css-propertyName-function )
<div id="id">Hello</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
//*****************************************************************************
function toggleOnClick($id) {
$("#" + $id).click(function() {
$("#" + $id).css('opacity', function(i, v) {
return v == 0 ? 1 : 0; //end of $("#"+$id).toggle
});
}); //end of $("#"+$id).click(function()
} //end of function toggleOnclick($id)
//*****************************************************************************
$(document).ready(function() {
toggleOnClick("id");
});
</script>
Iām using the following jQuery for hiding and showing content (toggle), as a tree navigation menu in my website. I found this code extremely useful because by clicking, it displays only one div at a time.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function show_region(chosen_region) {
$('.city_div').each(function(index) {
if ($(this).attr("id") == chosen_region) {
$(this).slideDown(200);
}
else {
$(this).slideUp(600);
}
});
}
</script>
<style type="text/css">
.city_div {display: none;}
</style>
North<br>
<div class="city_div" id="box01">Div #01</div>
Centre<br>
<div class="city_div" id="box02">Div #02</div>
South<br>
<div class="city_div" id="box03">Div #03</div>
The problem is that I can close a div only by opening another div.
How to close the div by a second click on it?
You can use slideToggle, change from slideDown to slideToggle:
function show_region(chosen_region) {
$('.city_div').each(function(index) {
if ($(this).attr("id") == chosen_region) {
$(this).slideToggle(200); // instead of slideDown
}
else {
$(this).slideUp(600);
}
});
}
First of all, don't use inline event handlers.
<script type="text/javascript">
$(document).ready(function() {
var boxes = $('.city_div');
$('.city-toggle').click(function(e) {
var box = $(this).next();
var isHidden = box.is(':hidden');
boxes.slideUp(600);
if(isHidden) {
box.slideDown(200);
}
e.preventDefault();
});
});
</script>
<style type="text/css">
.city_div {display: none;}
</style>
North
<div class="city_div" id="box01">Div #01</div>
Centre
<div class="city_div" id="box02">Div #02</div>
South
<div class="city_div" id="box03">Div #03</div>
Also, if your links don't go anywhere meaningful, use # as the href and make sure the boxes are visible by default. (Hide them using boxes.hide(); right at the start.)
Also also, <br> isn't what you should use there. <div>s are already block-level elements. If you want more padding, give them a top margin.
try this:
$(document).ready(function(){
$('.city_div').click(function(){
$(this).hide(); //or whatever code you want to hide it
});
});
that way when you click on a div, it will hide it.
Since you are using jQuery you could try using the jQuery.toggle function.
function show_region(chosen_region) {
$('#' + chosen_region).toggle('slide');
return false;
}
Keep track of the div you have clicked last:
var globalLastClickedButtonId;
$("div.city_div").click(function() {
if (globalLastClickedButtonId == $(this).attr("id")) {
$(this).hide();
} else {
var box = $(this).next().next();
var clickedId = $(this).attr("id");
$("div.city_div").each(function() {
if ($(this).attr("id") == clickedId)
box.slideDown(200);
else
box.slideUp(600);
}
}
globalLastClickedButtonId = $(this).attr("id");
});
First, why are you using such an old version of jQuery?
Second, your JavaScript can be simplified. jQuery works on sets; you don't need the .each, or loops.
Here is a working example: http://jsfiddle.net/gibble/25P9z/
Simplified HTML:
North<br>
<div class="city_div" id="box01">Div #01</div>
Centre<br>
<div class="city_div" id="box02">Div #02</div>
South<br>
<div class="city_div" id="box03">Div #03</div>ā
New JavaScript:
function show_region(e) {
var $target = $(e.target);
var chosen_region = $target.attr('data-contentDiv');
var openDiv = $('#' + chosen_region);
openDiv.slideDown(200);
$('.city_div').not(openDiv).slideUp(600);
}
Last, attach events, don't inline them in your HTML.
$('a[data-contentDiv]').click(show_region);ā
Because you are using an animation it is best to keep track of the div that is currently shown. If you don't, then you will start to see multiple divs showing if you click links in quick succession.
You can use this:
$(function() {
$("a").click(function(e) {
e.preventDefault();
var selectedDiv = $("#" + $(this).attr("href"));
var hide = selectedDiv.data("shown");
$(".city_div").slideUp(600);
$(".city_div").data("shown", false);
if (hide) {
selectedDiv.data("shown", false);
}
else {
selectedDiv.data("shown", true);
selectedDiv.slideDown(200);
}
});
});ā
Here is a working example
You should keep a variable with your old chosen region name
<script type="text/javascript">
var old_chosen_region="";
function show_region(chosen_region) {
$('.city_div').each(function(index) {
if (($(this).attr("id") == chosen_region)&&(chosen_region!=old_chosen_region)) {
$(this).slideDown(200);
old_chosen_region=chosen_region;
} else {
$(this).slideUp(600);
}
}
old_chosen_region='';
});
</script>
This allows you to 'remember' which region you chose last and, if the chosen one equals the last you close it.
You should set old_chosen_region='' in the end to let the tab reopen.
I've been fiddling with this:
http://jsfiddle.net/bXJhe/46/
What I need is for the time to advance to the next div id after timer has cycled. I click on "one" and it shows the current id, then it should advance to "two", "three"... and show their respective ids. I do not want to use jQuery's .remove() or .detach(). Any insight would be fantastic.
Have a big project due, and no hair left to pull out.
HTML:
<span id="bar"></span>
<span id="timer">00:05</span>
<div id="one">one</div>
<div id="two">two</div>
<div id="three">three</div>
<div id="four">four</div>
JS:
jQuery(document).ready(function() {
jQuery('div').not(':first').hide();
jQuery('a').hide();
timer(5)
});
// Timer
var GLOBAL_TIMER;
function timer(intCount) {
GLOBAL_TIMER = setInterval(function() {
var intTickLength = 5;
jQuery('#bar').css('width', intCount * intTickLength + 'px');
jQuery('#timer').html('00:0' + intCount--);
if (intCount < 0) {
jQuery('a').show('slow');
jQuery('a').click(function() {
id = jQuery(this).parent('div').attr('id');
alert('current id: ' + id);
jQuery(this).hide();
timer(5);
});
stopTimer();
}
}, 1000);
}
function stopTimer() {
clearInterval(GLOBAL_TIMER);
}
Check and see if this is what you need:
jQuery(document).ready(function() {
jQuery('div').hide();
currDiv = jQuery('#one');
timer(5);
});
// Timer
var GLOBAL_TIMER;
function timer(intCount) {
GLOBAL_TIMER = setInterval(function() {
var intTickLength = 5;
jQuery('#bar').css('width', intCount * intTickLength + 'px');
jQuery('#timer').html('00:0' + intCount--);
if (intCount < 0) {
currDiv.show('slow');
currDiv.click(function() {
id = currDiv.attr('id');
alert('current id: ' + id);
jQuery(this).hide();
currDiv = currDiv.next();
timer(5);
});
stopTimer();
}
}, 1000);
}
function stopTimer() {
clearInterval(GLOBAL_TIMER);
}
The cleanest solution, I think, is to use jQuery's data() mechanism to attach a variable to each <div>, signaling that it's the next one to be shown.
Also, you have <a> elements inside your <div> elements, and you're sometimes trying to show/hide one or the other...it seems to me it would be clearer to always operate on the same element. I chose the <div> elements.
So, first you'll want to hide all your <div> elements:
jQuery('div').hide();
Then you'll want to indicate that the "one" <div> is the next one to be shown:
jQuery('#one').data('nextToBeShown',true);
Then when you're going through each element (I go through <div>s instead of <a>s), you just have to look to see if it's the next element to be shown, and show it:
jQuery('div').each(function() {
current = jQuery(this);
if( current.data('nextToBeShown') ) {
current.show('slow');
}
});
Finally, when you click on the link, you'll want to move the "nextToBeShown" pointer:
jQuery('a').click(function() {
id = jQuery(this).parent('div').attr('id');
alert('current id: ' + id);
div = jQuery(this).parent();
div.hide();
div.data('nextToBeShown',false);
div.next().data('nextToBeShown',true);
timer(9);
});
And that gets you where you want.... See my updated jsFiddle here: http://jsfiddle.net/NjUg2/1/
jsBin demo
Referring to my old answer and my old DEMO to you....
the only thing you need to add is this:
////////////// old answer :
(function($){ // remap "$" to jQuery
$(function(){ // "Document Ready" shorthand
var divCounter = 0; ///// added
function timer(bar, intCount){
var elWidth = $(bar).width(), intTickLength=intCount, i;
function math(){
var m = Math.floor(intCount/60);
var s = intCount % 60;
if(m<10){m='0'+m;}
if(s<10){s='0'+s;}
$(bar).next('.timer').text(m+':'+s);
$(bar).width( elWidth*intCount/intTickLength );
if(intCount--<=0){
clearInterval(i);
showDiv(); /////// added
}
}
math();
i = setInterval(math, 1000);
}
timer('#bar',5);
////////////////////////////////
///////////// new answer :
$('div.box').hide(); // hide all initially
function showDiv(){
$('.box').hide().eq(divCounter%$('.box').length).show();
}
$('.box a').click(function(e){
e.preventDefault();
$('.box').hide();
divCounter++;
timer('#bar',5);
});
/////////////////////////////
});
})(jQuery);
HTML: add a class .timer to your span
<span id="bar"></span>
<span class="timer">00:05</span>
and add a common CLASS to your div elements:
<div class="box">one</div>
<div class="box">two</div>
<div class="box">three</div>
<div class="box">four</div>
If you have questions feel free to ask, and don't pull more hair out, but review some old questions for some solutions :)