how to stop repetition in jquery code? - javascript

I'm trying to make a image library and my code contains much repetition. Does anyone of you have an idea on how to make this work better?
Here is a exemple of the code
HTML
<div id="wrapper">
<div id="buttoncont">
<button id="all" type="button">All</button>
<button id="dog" type="button">Dog</button>
<button id="cat" type="button">Cat</button>
</div>
<img class="cat_img" src="http://upload.wikimedia.org/wikipedia/commons/2/22/Turkish_Van_Cat.jpg" />
<img class="dog_img" src="http://upload.wikimedia.org/wikipedia/commons/2/26/YellowLabradorLooking_new.jpg" />
</div>
JS
$("#cat").click(function () {
$("img.dog_img").hide();
$("img.cat_img").show();
});
$("#dog").click(function () {
$("img.cat_img").hide();
$("img.dog_img").show();
});
$("#all").click(function () {
$(".cat_img, .dog_img").show();
});

First: you need to set a default selected to make the Toggle work as expected.
Use CSS Classes to make the divs into one group(class) and bind the event to it, see the HTML:
<div id="wrapper">
<div id="buttoncont">
<button id="all" type="button">All</button>
<button class=toggle id="dog" type="button">Dog</button>
<button class=toggle id="cat" type="button">Cat</button>
</div>
<img class="cat_img" src="http://upload.wikimedia.org/wikipedia/commons/2/22/Turkish_Van_Cat.jpg" />
<img class="dog_img" src="http://upload.wikimedia.org/wikipedia/commons/2/26/YellowLabradorLooking_new.jpg" />
</div>
And on the Javascript Code, do a function to do it for you and use jQuery Toggle:
function toggleImg(){
$('img.dog_img').toggle();
$('img.cat_img').toggle();
}
$(".toggle").click(function () {
toggleImg();
});
$("#all").click(function () {
$(".cat_img, .dog_img").show();
});
But on the onLoad event of your page Toggle one of they indivually to make it the default selected, this way Toggling the two, always only one will be visible.
$('html').ready(function(){
$('img.cat_img').toggle();
});

function toggleImages(e){
$('img').hide();
$('img.'+e.target.id+'_img').show();
}
$("#cat").click(toggleImages);
$("#dog").click(toggleImages);
$("#all").click(function () {
$(".cat_img, .dog_img").show();
});
<div id="wrapper">
<div id="buttoncont">
<button id="all" type="button">All</button>
<button id="dog" type="button">Dog</button>
<button id="cat" type="button">Cat</button>
</div>
<img class="cat_img" src="http://upload.wikimedia.org/wikipedia/commons/2/22/Turkish_Van_Cat.jpg" />
<img class="dog_img" src="http://upload.wikimedia.org/wikipedia/commons/2/26/YellowLabradorLooking_new.jpg" />
</div>

I would do it like this
Keep the html as you have it.
$(".toggle").click(
function() {
$("."+ $(this).attr('id') + "_img").toggle()
}
);
$("#all").click(
function() {
$("img[class$='_img']").show()
}
);
This way you can add as many images and buttons as you want without modifying your javascript
Here is a jsFiddle

You can use this :
$('#buttoncont button').click(function(){
if(this.id=='all'){
$('img').show();
}else{
$('img').hide().filter('.'+ this.id +'_img').show();
}
})
Fiddle : http://jsfiddle.net/b65EL/

An idea
$("#all").click(function(){
$(".cat_img, .dog_img").show();
}
$("#dog, #cat").click(function(){
$("img."+this.id+"_img").toggle();
}

Remove the ID attributes on the buttons unless you need them for something else.
Add a custom attribute to the buttons, such as:
<button id="cat" type="button" image-clicker="cat_img">Cat</button>
Then add this jquery to the page (I didn't test this so you may have to fix minor issues with it):
$(function(){
$("[image-clicker]").each(function(){
var buttonClicked = $(this);
var targetID = buttonClicked.attr("image-clicker");
var targetElement = $("#"+targetID);
$(this).click(function(){
// hide other images
$("[image-clicker]").hide();
targetElement.show();
});
};
});

Depending on the surrounding HTML, you may have to modify this. But with JUST the HTML you've shared, you can do this:
$(document).on('click', 'button', function(){
$('img').hide();
$("." + this.id + "_img").show();
//Workaround for '#all'
if( this.id === 'all' ){
$('img').show();
}
});
You could also modify your HTML to take advantage of the data- attribute:
<div id="wrapper">
<div id="buttoncont">
<button data-show="dog, cat" type="button">All</button>
<button data-show="dog" type="button">Dog</button>
<button data-show="cat" type="button">Cat</button>
</div>
<img class="cat_img" src="http://upload.wikimedia.org/wikipedia/commons/2/22/Turkish_Van_Cat.jpg" />
<img class="dog_img" src="http://upload.wikimedia.org/wikipedia/commons/2/26/YellowLabradorLooking_new.jpg" />
</div>
JS (untested, but should work):
$(document).on('click', 'button', function(){
var arrShow = this.getAttribute('data-show').split(/\s*,\s*/);
$('img').hide();
for( var i = arrShow.length; i-- > 0; ){
$('.' + arrShow[i] + '_img').show();
}
});

Related

How to increment a number inside <p> in html upon click

How do I increment a number in p tag in HTML upon click on a picture? The code that I have tried seems to be not working.
$(document).on("click", ".minusbutton", function() {
$('.parquantity').html(parseInt($('.parquantity').html(), 10) + 1)
alert('you clicked on button #');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="amountCounter">
<img class="minusbutton" src="/mcdb/Logos/minus.png" alt="minus">
<div class="quantity">
<p class="parquantity">1</p>
</div>
<img class="plusbutton" src="/mcdb/Logos/plus.png" alt="plus">
</div>
First, attach the click event to both images then you could use text() instead of html() since you deal with the text value (you need no HTML tags).
You could use ++/-- to add/subtract one when you click :
$(document).on("click", ".plusbutton", function() {
var parquantity = parseInt($('.parquantity').text(), 10);
$('.parquantity').text(++parquantity);
});
$(document).on("click", ".minusbutton", function() {
var parquantity = parseInt($('.parquantity').text(), 10) - 1;
if (parquantity > 0) {
$('.parquantity').text(parquantity);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="amountCounter">
<img class="minusbutton" src="/mcdb/Logos/minus.png" alt="minus">
<div class="quantity">
<p class="parquantity">1</p>
</div>
<img class="plusbutton" src="/mcdb/Logos/plus.png" alt="plus">
</div>
You can increase and decrease target number in one event listener. Also using .text( fucntion ) the code is simpler
$(document).on("click", ".minusbutton, .plusbutton", function() {
var ele = $(this);
$('.parquantity').text(function(i, t){
return ele.is(".plusbutton") ? +t+1 : +t-1;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="amountCounter">
<img class="minusbutton" src="/mcdb/Logos/minus.png" alt="minus">
<div class="quantity">
<p class="parquantity">1</p>
</div>
<img class="plusbutton" src="/mcdb/Logos/plus.png" alt="plus">
</div>

Showing and hiding a div with JS/jQuery in a Wordpress loop

I am looking for some help using JS or jQuery to show and hide a div. This I am familiar with but the issue arrises while using this in a Wordpress loop. I have done this before but it was in a bit of a hack-y way and I thought I would try and find the correct way.
This is loop code:
<div class="row">
<div class="col-md-8 ">
<img src="WP IMAGE HERE" alt="">
</div>
<div class="col-md-4 offers">
<h2 class="offers--title">WP TITLE HERE</h2>
<hr class="offers--hr">
<p class="offers--bio">WP OFFER INFO HERE</p>
<button type="button" href="#" onclick="showHide()" class="btn btn-crs-sm ">Redeem this offer</button>
<div id="voucher"> THIS IS THE DIV TO BE SHOWN/HIDDEN</div>
</div>
</div>
My general plan of action was this:
Add an onclick to the button code that is in the loop:
<button type="button" href="#" onclick="showHide()" class="btn btn-crs-sm ">Redeem this offer</button>
show/hide using this code:
function showHide() {
var x = document.getElementById("voucher");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
I then used:
$(document).ready(function() {
$("div[id^='vouche']").each(function(i) {
$(this).attr('id', "voucher" + (i + 1));
});
});
to add a number to the end of each ID called "voucher"
I then duplicated the first batch of code shown above three times to be called showHide1, 2 & 3 and refer to the div elements voucher1, 2 & 3.
The next issue is to then alter the code of the onclick in the buttons in the loop (so it says showHide1,2,3() etc.) – I tried to do this in jQuery but this was where I came unstuck and decided to look for help.
There must be a much easier & more efficient way of doing this!
Any help would be greatly appreciated.
EDIT/UPDATE:
I have now edited my jQuery to this:
$(document).ready(function() {
$("div[id^='vouche']").each(function(i) {
$(this).attr('id', "voucher" + (i + 1));
});
});
$(document).ready(function() {
$("button[id^='voucherButto']").each(function(i) {
$(this).attr('id', "voucherButton" + (i + 1));
});
});
$( "#voucherButton1" ).click(function() {
$( "#voucher1" ).toggle( "slow", function() {
});
});
$( "#voucherButton2" ).click(function() {
$( "#voucher2" ).toggle( "slow", function() {
});
});
$( "#voucherButton3" ).click(function() {
$( "#voucher3" ).toggle( "slow", function() {
});
});
This works correct as expected (adding the right numbers to the right Id's, etc) however it doesn't show/and hide correctly. Any ideas?
You can get elements with jQuery by $('#yourId'). jQuery has already a method which allows you to display or hide an element by just calling toggle()
as described in their docs.
Your showHide() function can be replaced by this:
function showHide(yourPostId) {
$('#voucher-' + yourPostId).toggle();
}
You have to extend each loop with an attribute that is related to the current iteration. For example with the post id...:
<?php while (have_posts()): ?>
<div class="row">
<div class="col-md-8 ">
<img src="WP IMAGE HERE" alt="">
</div>
<div class="col-md-4 offers">
<h2 class="offers--title">WP TITLE HERE</h2>
<hr class="offers--hr">
<p class="offers--bio">WP OFFER INFO HERE</p>
<button type="button" href="#" onclick="showHide(<?php the_ID(); ?>)" class="btn btn-crs-sm ">Redeem this offer</button>
<div id="voucher-<?php the_ID(); ?>"> THIS IS THE DIV TO BE SHOWN/HIDDEN</div>
</div>
</div>
<?php endwhile; ?>

Get parent of the parent of div

I have searched and tried many things to do this such as closest() and parents() and parent() and find() But i couldnt make it to work at all .
I have this html
<div class='message_holder area2 user45 chatid32'>
<a class='avatar' title='jhon'>
<img height='28px' width = '28px' src="link to image" />
</a>
<div class='flag_holder'>
<div class='edited png32'></div>
<div class=' png32'></div>
</div>
<div class='message user_chat'> hghgghgh</div>
<div class='like_holder'>
<div class='chattime'>02-12 22:16</div>
<div class='likepng'></div>
<div class='likescore'>5</div>
<div class='unlikescore'>0</div>
<div class='unlikepng'></div>
<div class="like">
<div class="editpng"></div>
<div class="deletepng"></div>
</div>
</div>
</div>
So what i want is when i click on on div class deletepng i want to remove the two divs unlikepng and likepng .
this js
$(document).on ("click", ".deletepng", function () {
$this = $(this);
//alert( $this.closest(".like").html()); I could just make this to work
// alert( $this.parents(".like_holder").html()); wont work
// alert( $this.closest(".like_holder").html()); wont work
// alert( $this.parent().parent().html()); wont work
// alert( $this.closest(".like_holder").find(".like_holder").html()); wont work
});
I just wonder why they dont work those my trying . Where it can be my mistake ?
EDIT:
i dont know if this have a role or not , i have what i tried inside Dialog box like that
$(document).on ("click", ".deletepng", function () {
$this = $(this);
$('<div>' + c_delete + '</div>').dialog({
resizable: false,
buttons: {
"Yes": function() {
chat_text_h.html('<div class="removed"> Removed</div>'); // do something here
$(this).dialog("close");
//alert( $this.closest(".like").html()); I could just make this to work
// alert( $this.parents(".like_holder").html()); wont work
// alert( $this.closest(".like_holder").html()); wont work
// alert( $this.parent().parent().html()); wont work
// alert( $this.closest(".like_holder").find(".like_holder").html()); wont work
}
}
});
});
use closest then use the second argument as the context.
$(document).on("click", ".deletepng", function() {
var $holder = $(this).closest('.like_holder');
$('.likepng, .unlikepng', $holder).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='message_holder area2 user45 chatid32'>
<a class='avatar' title='jhon'>
<img height='28px' width='28px' src="link to image" />
</a>
<div class='flag_holder'>
<div class='edited png32'></div>
<div class=' png32'></div>
</div>
<div class='message user_chat'>hghgghgh</div>
<div class='like_holder'>
<div class='chattime'>02-12 22:16</div>
<div class='likepng'>like</div>
<div class='likescore'>5</div>
<div class='unlikescore'>0</div>
<div class='unlikepng'>unlike</div>
<div class="like">
<div class="editpng"></div>
<div class="deletepng">delete</div>
</div>
</div>
</div>
EDIT
Since your update, you need to set a global variable to remember $this or the container/holder. try this:-
var $holder;
$(document).on("click", ".deletepng", function() {
$holder = $(this).closest('.like_holder');
$('<div>' + c_delete + '</div>').dialog({
resizable: false,
buttons: {
"Yes": function() {
chat_text_h.html('<div class="removed"> Removed</div>');
$(this).dialog("close");
$('.likepng, .unlikepng', $holder).remove();
}
}
});
});
$this.closest(".like").html(); => this will return HTML of parent div, where delete button is. Not removing the element
$this.parents(".like_holder").html() => this will return html of div.message_holder. Not removing the element.
$this.closest(".like_holder").html() => this will return html of div.like_holder
$this.parent().parent().html(); close enogh, but still far => html of div.like_holder
$this.closest(".like_holder").find(".like_holder").html(); return null => no child element with class like_holder in div.like_holder.
Kind of example
$(document).on ("click", ".deletepng", function () {
var $parent = $(this).parent().parent();
$parent.find('.likepng').remove();
$parent.find('.unlikepng').remove();
});
.deletepng{
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='message_holder area2 user45 chatid32'>
<a class='avatar' title='jhon'>
<img height='28px' width = '28px' src="http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg" />
</a>
<div class='flag_holder'>
<div class='edited png32'></div>
<div class=' png32'></div>
</div>
<div class='message user_chat'> hghgghgh</div>
<div class='like_holder'>
<div class='chattime'>02-12 22:16</div>
<div class='likepng'> like me</div>
<div class='likescore'>5</div>
<div class='unlikescore'>0</div>
<div class='unlikepng'> unlike me</div>
<div class="like">
<div class="editpng"></div>
<div class="deletepng">delete button</div>
</div>
</div>
</div>
UPDATE
If you want to make it from dialog box, or other things - you can't use this variable. This is not making any sense. You should provide unique id to your message_box and then use it, like
$(id_of_message_box).find('.likepng, .unlikepng').remove()
or as I can see from your code:
var $parent = $this.parent().parent();
$parent.find('.likepng, .unlikepng').remove();
It means you should use $this in your function instead of $(this)
You can access the parents parent of your $(this) like:
var likeholder;
likeholder = $(this).parent().parent();
However this is generally ill advised. You'll have a jquery object though.
Let me know how you get on
In order to select the parent of a parent of an element you try this:
$(document).on ("click", ".deletepng", function () {
alert( $($(this).parent()).parent().html());
});
Since you can only execute the parent() method on Jquery Objects.
Here's an example unrelated to your code. JSFiddle.
Try this, you need sibling of parent;
alert( $this.closest(".like").parent().find(".unlikescore").html());
alert ($this.closest('.like').siblings('.unlikepng').html()) ;
working js fiddle

Javascript: Change background of all images inside div

I would like to change the background of all images inside a div with a JS function:
My div:
<div>
<div id="avatar_container">
<img src="a.png" onclick="myfunction()" />
<img src="b.png" onclick="myfunction()" />
</div>
</div>
My function:
function myfunction(){
//I tried this two methods
document.getElementById("avatar_container").getElementsByTagName('img').css({'background' : 'green'});
document.getElementById("avatar_container").getElementsByTagName('img').style.backgroundColor = "green";
}
that's solve your problem
<div id="avatar_container">
<img src="a.png" class="myClass1" />
<img src="b.png" class="myClass1" />
</div>
Js: (important Notice: use js code after html codes)
var elems = document.getElementsByClassName('myClass1'), i;
for (i in elems) {
elems[i].style.backgroundColor = "green";
}
}
but i suggestion you to use and learn Jquery ,
jquery is a Javascript Framework witch make everything's very easy for you with less coding
with Jquery You can do it simplest like this
$('#avatar_container .myClass1').css('backgroundcolor','green');
and if you wanna attach click event
$('#avatar_container .myClass1').click(function() {
$(this).css('backgroundcolor','green');
});

Change <button> text if element is :hidden or :visible

I have a button that toggles the playlistHolder div. In addition, when '.albumImage a' is selected, it also unhides the playlist. I am trying to change the text of the button to 'Show Playlist' if the playlist is hidden and 'Hide Playlist' if it is not hidden. I have tried click functions with if(('.playlist').is(:hidden)) but have not had any luck with getting it to work. I am new to Jquery so I understand that my code below can use much improvement, here is my setup now that works when the album image is selected as well as when the toggle button is selected without changing the text:
HTML
<div class="togglePlaylist">
<button id="togglePlaylistBT">Show/Hide Playlist</button>
<!-- POPUP LAUNCHER -->
</div>
<div class="playlistHolder">
<div class="componentPlaylist">
<div class="playlist_inner">
<!-- playlist items are appended here! -->
</div>
</div>
<!-- preloader -->
<div class="preloader"></div>
</div>
<div class="albumWrapper">
<div class="albumCovers">
<div class="albumImage"> <img class="img-responsive" src="media/music/Album_Covers/Swag_Brothers.jpg" alt="thumb" />
<p class="nowPlaying">Now Playing</p>
</div>
</div>
</div>
Javascript/JQuery
$('#togglePlaylistBT, .albumImage a').on('click', function() {
var $this = $('#togglePlaylistBT');
if($('.playlistHolder').is(':visible'))
{
$('.playlistHolder').hide('slow');
$this.text('Hide Playlist');
}
else
{
$('.playlistHolder').show('slow');
$this.text('Show Playlist');
}
});
Try this snippet of code:
$('.togglePlaylist button').on('click', function() {
var $this = $(this);
if($('.playlistHolder').is(':visible'))
{
$('.playlistHolder').hide();
$this.text('Hide Playlist');
}
else
{
$('.playlistHolder').show();
$this.text('Show Playlist');
}
});
Working JSFiddle
When you hide and show the playlist just run document.getElementById("togglePlaylistBT").value="Show Playlist";
For example:
function change()
{
var elem = document.getElementById("playlistButton");
if (elem.value=="Open Playlist") { elem.value = "Close Playlist"; closeBox(); }
else { elem.value = "Open Playlist"; openBox(); }
}
function openBox() {
alert("open");
}
function closeBox() {
alert("closed");
}
<input onclick="change()" type="button" value="Open Playlist" id="playlistButton"></input>
Make sure to change openBox() and closeBox() functions to your box code!

Categories