-- I'm new to jQuery disclaimer --
I have two images:
https://i.imgur.com/l2H17fn.jpg
https://i.imgur.com/5nlOoyc.jpg
I'd like to show the second one in place of the first one after it's been clicked on five times.
To get the image to replace after one click, I have this:
HTML:
<div class = "dog">
<img id="happy" src="https://i.imgur.com/l2H17fn.jpg">
</div>
jQUERY:
$('.dog').click(function(e){
e.preventDefault();
$("#happy").attr('src',"https://i.imgur.com/5nlOoyc.jpg");
return false;
});
Link to codepen.
Now what if I want to replace the image after the fifth click? What would that look like?
You can keep track of clicks with a variable:
// initialize click count to zero.
var clicks = 0;
$('.dog').on('click', function() {
// increment click count.
clicks++;
// FOR DEMO - output the click count to the console.
// console.log(clicks);
// if clicks is greater than or equal to 5...
if (clicks >= 5) {
// ... change the image ...
$("#happy").attr('src', "https://i.imgur.com/5nlOoyc.jpg");
// .. and remove this click handler.
$(this).off('click');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dog">
<img id="happy" src="https://i.imgur.com/l2H17fn.jpg">
</div>
Here you go...I think the trick is to have a global semaphore variable...This one toggles between though...:)
var clicks = 0;
$('.dog').on('click', function(e){
clicks++;
if(clicks >= 5){
if($('#happy').attr('src') !== 'https://i.imgur.com/5nlOoyc.jpg'){
$("#happy").attr('src',"https://i.imgur.com/5nlOoyc.jpg");
}else{
$("#happy").attr('src',"https://i.imgur.com/l2H17fn.jpg");
}
clicks = 0;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "dog">
<img id="happy" src="https://i.imgur.com/l2H17fn.jpg">
</div>
Related
I am following this Js fiddle
http://jsfiddle.net/ryt3nu1v/10/
My Result:
I am making a slider that display age as I have an array that following ages
15,25,35,45,55
I am trying to display them in slider
expected behavior is to see the next age when i click on next button
Code that I used from fiddle according to my need is
//Age slider
$('div.result-age:gt(0)').hide(); //Hide all but the first one
var $allSlides = $('div.result-age'),
traverseDefault = "first", //set the defaults
actionDefault ="arrow-next";
$('.arrow-next,.selected-arrow-left-pointer').click(function(){
var traverse = traverseDefault,
action = actionDefault;
if($(this).is('.selected-arrow-left-pointer')){ //if action is prev
traverse = "last"; //set traverse to last in case nothing is available
action = "selected-arrow-left-pointer"; //set action to prev
}
var $curr = $allSlides.filter(':visible'), //get the visible slide
$nxtTarget = $curr[action](".result-age"); //get the next target based on the action.
$curr.stop(true, true).fadeIn(1000).hide(); //hide current one
if (!$nxtTarget.length){ //if no next
$nxtTarget = $allSlides[traverse](); //based on traverse pick the next one
}
$nxtTarget.stop(true, true).fadeIn(1000); //show the target
});
//age slider end
And this is my HTML
<div class="result-box">
<div class="selected-arrow-left-pointer"></div>
<div class="result-age"><span><h4 v-for="(row,key,index) in ages">ALL ages here currently being display all at once</h4></span></div>
<div class="arrow-next"></div>
</div>
My current style is that age will be displayed in center with left and right sides having next and previous button
What am I missing?
Your v-for is creating mutliple h4 tag but you need create result div for each numbers so move your v-for inside your div tag .Then , you are using wrong values for actionDefault and action it should be next & prev where next refer to next slide and prev refer to previous slide not the classnames .
Demo Code :
$('div.result-age:gt(0)').hide();
var $allSlides = $('div.result-age'),
traverseDefault = "first",
actionDefault = "next"; //use next ..refer next node
$('.arrow-next,.selected-arrow-left-pointer').click(function() {
var traverse = traverseDefault,
action = actionDefault;
if ($(this).is('.selected-arrow-left-pointer')) {
traverse = "last";
action = "prev"; //use prev..refer prev..
}
var $curr = $allSlides.filter(':visible');
$nxtTarget = $curr[action](".result-age");
$curr.stop(true, true).fadeIn(1000).hide();
if (!$nxtTarget.length) {
$nxtTarget = $allSlides[traverse]();
}
$nxtTarget.stop(true, true).fadeIn(1000);
});
span.next,
span.prev {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="result-box">
<div class="selected-arrow-left-pointer">
<< </div>
<!--your div should have ` v-for="(row,key,index) in ages"`-->
<div class="result-age"><span><h4>1</h4></span></div>
<div class="result-age"><span><h4>2</h4></span></div>
<div class="result-age"><span><h4>3</h4></span></div>
<div class="arrow-next"> >> </div>
</div>
I found the issue, you were using arrow-next instead of next, and selected-arrow-left-pointer instead of prev. Check the below working snippet. The data can be provided dynamically as you wish, currently I have given static data.
The next and prev are reserved keywords and hence the $curr[action] was expecting a function in return, while in your case it was `$curr['arrow-next'] instead of $curr['next'], which was returning undefined, and hence the error occurred.
//Age slider
$("div.result-age:gt(0)").hide(); //Hide all but the first one
var $allSlides = $("div.result-age"),
traverseDefault = "first", //set the defaults
actionDefault = "next";
$(".next,.prev").click(function () {
var traverse = traverseDefault,
action = actionDefault;
if ($(this).is(".prev")) {
//if action is prev
traverse = "last"; //set traverse to last in case nothing is available
action = "prev"; //set action to prev
}
var currentData = $allSlides.filter(":visible"), //get the visible slide
$nxtTarget = currentData[action](".result-age"); //get the next target based on the action.
currentData.stop(true, true).fadeIn(1000).hide(); //hide current one
if (!$nxtTarget.length) {
//if no next
$nxtTarget = $allSlides[traverse](); //based on traverse pick the next one
}
$nxtTarget.stop(true, true).fadeIn(1000); //show the target
});
.next, .prev {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="result-box">
<div class="prev"><</div>
<div class="result-age">
<span><h4>ALL ages here currently being display all at once</h4></span>
</div>
<div class="result-age">
<span><h4>2</h4></span>
</div>
<div class="result-age">
<span><h4>3</h4></span>
</div>
<div class="result-age">
<span><h4>4</h4></span>
</div>
<div class="result-age">
<span><h4>5</h4></span>
</div>
<div class="next">></div>
</div>
I've created this little fancy jQuery Snippet to toggle the class of an element in an interval:
setInterval(function(){$('.grid-item .slide-image').toggleClass('active')}, 800);
The script works fine! Now I got multiple elements with the base-class .slide-image in the wrapper .grid-item.
<div class="grid-item">
<div class="slide-image"><img src="http://www.placehold.it/500x500/233953"></div>
<div class="slide-image"><img src="http://www.placehold.it/500x500/03144b"></div>
<div class="slide-image"><img src="http://www.placehold.it/500x500/030a4b"></div>
</div>
Is there a way to rewrite the snippet so the second .slide-image gets the class .active after the first one? Then the third element and so on...
The Problem: The amout of .slide-image-elements is no defined. In some cases there are two of them, in another there are four elements.
Check out my CodePen!
Try this
var slides = $('.grid-item .slide-image'), // cache slides
counter = 0; // global counter
setInterval(function(){
slides.removeClass('active'); // remove active class
slides.eq(counter).addClass('active'); // add active class
counter++;
if (counter == slides.length) counter = 0; // reset counter after last slide
}, 800);
Updated CodePen
You can check if current active element id last or not. if it is, then show first element in set else show next sibling element:
$(function(){
var slides = $('.grid-item .slide-image');
setInterval(function(){
var currentactive = $('.active');
var _target = currentactive.is(':last-child') ? slides.first() : currentactive.next();
slides.removeClass('active')
_target.addClass('active')
}, 800);
});
Working Demo
I have a little app that adds items to a list. The items appear with a button next to them, I want to be able to press that button to add a (text-decoration: line-through). I have tried a few different things but nothing seems to work (the Javascript to add items, delete the last item, add classes to the new li elements, etc. All that works fine, my problem is only with the JQuery part, more comments on the code itself).
HTML
<html>
<body>
<h1> Shopping List </h1>
<button id="add"> Add </button>
<input type="text" id="input" placeholder="Enter Items"> </input>
<button id="remove"> Remove Last </button>
<ul id="list">
</ul>
</body>
</html>
Js/Jq:
document.getElementById("add").addEventListener('click', function() {
var check = document.createElement("button");
var input = document.getElementById("input").value;
var newEl = document.createElement("li");
var newText = document.createTextNode(input);
var buttonText = document.createTextNode("Check");
newEl.className = "liEl";
newEl.appendChild(newText);
newEl.appendChild(check);
check.setAttribute("class", "checked");
check.appendChild(buttonText);
/* Problem starts here */
$("button.checked").on('click', function() {
$('li.liEl').css('text-decoration: line-through');
/* It should get the button with the class "checked" and on click, make the li elements with class "liEl" to have that css... */
}
);
var position = document.getElementsByTagName("ul")[0];
position.appendChild(newEl);
document.getElementById("input").value = "";
document.getElementById('input').onkeypress = function(e) {
if (e.keyCode == 13) {
document.getElementById('add').click(); /* adds an event listener to the submit text, keyCode 13 equals the enter key so when it's pressed it presses the add button. */
}
}
});
/* Delete last item function: */
document.getElementById("remove").addEventListener('click', function() {
var els = document.getElementsByTagName("li");
var removeEl = els[els.length - 1]; // <-- fetching last el, If els is an array, it has indices from 0 to els.length - 1. 0 is the first, els.length - 1 is the last index.
var containerEl = removeEl.parentNode;
containerEl.removeChild(removeEl);
});
Use style like $('li.liEl').css('text-decoration','line-through');
Your jQuery css function is wrong, you need to provide two parameter to set css value (see this: css-property-name-value).
Your selector syntax ($('li.liEl')) is not right, it would return all <li> element, not the one the clicked button is located.
You can use this: $(this).parent().css('text-decoration', 'line-through');.
Your code contain some bug, the last added button would not trigger the function. It is because your click function is added before the new element added to DOM. And it would cause your click function to be triggered multiple time for earlier added button.
Here's the snippet for fixed code. Since you already using jQuery, I change several native java script native element query and event handler whith jquery syntax.
$(function () {
$("#add").click(function(evt) {
var input = $('#input').val();
var check = $('<button class="checked">Check</button>');
var newEl = $('<li class="liEl"></li>');
newEl.append(input);
newEl.append(check);
$(check).click(function(evt) {
$(this).parent().css('text-decoration', 'line-through');
});
$('#list').append(newEl);
$('#input').val('');
});
$('#remove').click(function(evt) {
var lastEl = $('li.liEl').last();
lastEl.remove();
});
$('#input').keypress(function(evt) {
if (evt.keyCode === 13) {
$("#add").click();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<body>
<h1> Shopping List </h1>
<button id="add"> Add </button>
<input type="text" id="input" placeholder="Enter Items" />
<button id="remove"> Remove Last </button>
<ul id="list"></ul>
</body>
I have ten buttons. When one is clicked I want the corresponding div to fade in and when another button is clicked I want the div to fade out and the new div to fade in.
My method is not working correctly because my knowledge of JS is limited. I am currently running with something like this:
var active01 = false;
var active02 = false;
var active03 = false;
var active04 = false;
var active05 = false;
$("#button1").click(function () {
active02 = false;
active03 = false;
active04 = false;
active05 = false;
active01 = true;
});
if(active01){
//fadein;
} else{
//fadeout;
}
Is there a way to set all the active buttons to false without having to write everything out each time? Something like this....
var active01 = false;
var active02 = false;
var active03 = false;
var active04 = false;
var active05 = false;
var actives = active01, active02, active03, active04, active05;
$("#button1").click(function () {
actives = false;
active01 = true;
});
Optionally you could use data elements to help you out. For instance...
<input type="button" data-key="1">
<input type="button" data-key="2">
<div data-key="1"></div>
<div data-key="2"></div>
Given this setup you could have event handlers on the inputs. When on is clicked, fade all your divs. Then find the div that corresponds to your input with $('div').filter('[data-key="'+ $(this).data('key') +'"]') and then you can perform your fade in logic on it.
use an array
var active = [];
for(i = 0; i<10; i++){
active.push(false);
}
$("#button1").click(function () {
for(i = 0; i<active.length; i++){
active[i] = false;
}
active[1] = true;
});
I'd use it like this
$('.fade-target-container').on('click', function() {
var targetContainer = $(this).attr('data-target');
$('.fadeable-div').hide('fast');
$('#' + targetContainer).show('fast');
});
.fadeable-div {
display:none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="fade-target-container" data-target="div1">My Button 01</button>
<button class="fade-target-container" data-target="div2">My Button 02</button>
<button class="fade-target-container" data-target="div3">My Button 03</button>
<button class="fade-target-container" data-target="div4">My Button 04</button>
<button class="fade-target-container" data-target="div5">My Button 05</button>
<div class="fadeable-div" id="div1">DIV1</div>
<div class="fadeable-div" id="div2">DIV2</div>
<div class="fadeable-div" id="div3">DIV3</div>
<div class="fadeable-div" id="div4">DIV4</div>
<div class="fadeable-div" id="div5">DIV5</div>
Hard to give an exact answer without seeing the HTML, but I can give it to you in pseudocode and we can go from there.
You don't need variables to do this . . . from what you've stated, you want all the divs to be hidden, unless their associated button is clicked, and then, only that one div should show. You can do this with jQuery selectors pretty easily.
$(".commonButtonClass").on("click", function() {
$(".commonDivClass").fadeOut();
$("...SELECTOR_TO_FIND_THE_ASSOCIATED_DIV...").fadeIn();
});
Each div would need to have the commonDivClass class assigned to them and the buttons need to have the commonButtonClass assigned to them. then, based on whatever relationship ties the buttons to their specific divs, you would need to create the correct selector to replace "...SELECTOR_TO_FIND_THE_ASSOCIATED_DIV...".
Using this, you don't need to track the states of the divs, just make sure that they are all hidden, before you show the one that is paired with the button that was clicked.
(P.S. - If you provide the actual HTML, I can give you a more exact answer, but, hopefully, you can figure it out from what I've posted.)
Objective
What method to use to make item 3 move to another container.
Then if click again return the item to previous position
this function should be apply to all items.
Jquery
$('#item3').click(function(){
// What method to use to make item_1 move to another container.
// Then if click again return the item to previous position
});
Check DEMO
HTML
<div id="start">
<div class="element">one</div>
<div class="element">two</div>
<div class="element">three</div>
</div>
<div id="target"></div>
jQuery
$('.element').click(function() {
var cont = $(this).parent().attr('id');
if (cont == 'start') {
var place = '#target';
} else {
var place = '#start';
}
$(place).append($(this));
});
you can use drag and drop plugin of jquery UI.
if you cont want use this then you can try this code by onClick finction....
.JS
function onclickIteam(iteamId){
var x = if('#iteamId').html();
if(if('#iteamId').parent().prop("id") == "my_inventory"){
//$('#iteamId').detach();
$('#server_inventory').append(x);
}else{
//$('#iteamId').detach();
$('#my_inventory').append(x);
}
`}`