jquery hover and selected issue - javascript

http://www.kars4kids.org/charity/v2/nirangahtml/program_pop/meet_animals.asp
above link,
when I select one of icon at below.
it's change to selected states, but problem is I need to restrict hover effect and further selecting for that Icon . ( since I am using Image changing).
below is the my complete, jquery code.
$(document).ready(function(){
$('#animal_content_text_horse').css("display", "block");
$('#animal_pic_horse_span').css("display", "block");
$('#page_animal_img_horse').css("display", "block");
$('.animal_thumb_link').each(function() {
$(this).click(function(e) {
e.preventDefault();
default_set($(this).attr('id'));
$(".animal_thumb_link").removeClass("thumbselected");
$(this).addClass("thumbselected");
$(".animal_thumb_link").find('img').addClass("imgHoverable");
$(this).find('img').removeClass("imgHoverable");
});
});
// Change the image of hoverable images
$(".imgHoverable").hover( function() {
var hoverImg = HoverImgOf($(this).attr("src"));
$(this).attr("src", hoverImg).hide().fadeIn(0);
}, function() {
var normalImg = NormalImgOf($(this).attr("src"));
$(this).attr("src", normalImg).show();
}
);
function HoverImgOf(filename)
{
var re = new RegExp("(.+)\\.(gif|png|jpg)", "g");
return filename.replace(re, "$1_r.$2");
}
function NormalImgOf(filename)
{
var re = new RegExp("(.+)_r\\.(gif|png|jpg)", "g");
return filename.replace(re, "$1.$2");
}
});
function default_set(obj12){
var arr = ["horse_content", "camel_content", "peacock_content", "goat_content", "donkey_content", "rooster_content", "sheep_content", "alpacas_content", "cynthia_content", "rabbit_content", "cow_content"];
var arr2 = ["../images/horse_thumb.gif", "../images/camel_thumb.gif", "../images/peacock_thumb.gif", "../images/goat_thumb.gif", "../images/donkey_thumb.gif", "../images/rooster_thumb.gif", "../images/sheep_thumb.gif", "../images/alpacas_thumb.gif", "../images/cynthia_thumb.gif", "../images/rabbit_thumb.gif", "../images/cow_thumb.gif"];
for ( var i = 0; i <= arr.length; i++ ) {
if ( arr[ i ] === obj12 ) {
old_url = $("#" + obj12).children('img').attr('src');
new_url = old_url.replace(/thumb/,'thumb_r');
$("#" + obj12).children('img').attr('src',new_url);
}else{
$('#' +arr[ i ]).children('img').attr('src',arr2[ i ]);
}
}
}
function load_page(obj1,obj2,obj3){
/* detect current div if so hide */
current_pagepharadiv = document.getElementById("pagepharadiv_hidden").value;
current_pageheadertext = document.getElementById("pageheadertext_hidden").value;
current_pageimage = document.getElementById("pageimage_hidden").value;
$('#' + current_pagepharadiv).css("display", "none");
$('#' + current_pageheadertext).css("display", "none");
$('#' + current_pageimage).css("display", "none");
image_hover(obj1);
image_hover(obj2);
$('#' + obj3).fadeIn("fast");
//image_hover(obj3);
//$('#' + obj1).fadeIn("fast");
//$('#' + obj2).fadeIn("fast");
document.getElementById("pagepharadiv_hidden").value = obj1;
document.getElementById("pageheadertext_hidden").value = obj2;
document.getElementById("pageimage_hidden").value = obj3;
}
can you please advice guys,
cheers!

It seems to me that you're really making things more complicated than they need to be. Here's how I would implement the page:
Bottom squares as divs, make the images transparent pngs
Change bottom square color using css :hover
Generate the entire top content on the server for each animal in a div: so you have 11 divs one after the other, instead of having to hide/show things in 3 places. In my code example below I assume they have the class animal-content
Add the id of each top div as a html5 data attribute to the corresponding thumb link
This way all you need to do in jQuery is:
$(".animal_thumb_link").click(function() {
var topId = $(this).data("topId");
$(".animal_thumb_link").removeClass("thumbselected");
$(this).addClass("thumbselected");
$(".animal-content").toggle(function() { return this.id === topId; });
});

Related

how to append a div content to a class only once?

I have several images as slide. On clicking next button, images are being slide shown but i want to add a text for each image over the image.
javacsript code:
afterShow: function( instance, current ) {
//alert($(this).find('img').attr('alt'));
var url = window.location.href;
var cat = url.substring(url.lastIndexOf('#') + 1);
var cats = cat.split('-');
catId= cats[0];
var index=catId+$("[data-fancybox-index]").html();
//alert($("[data-fancybox-index]").html());
//$('.fancybox-slide').children(".imagecontainer").remove();
//alert($("#d_" + index).length);
if($("#d_" + index).length == 0) {
var strDiv='<div id="d_'+index+'" class="centerdivCont"></div>';
$(".fancybox-content").append(strDiv);
return false;
}
/*if($("#d_" + index).length> 0) {
var strDiv='<div id="d_'+index+'" class="centerdivCont"></div>';
$(".fancybox-content").remove(strDiv);
}else{
var strDiv='<div id="d_'+index+'" class="centerdivCont"></div>';
$(".fancybox-content").append(strDiv);
}*/
//alert($("#d_" + index).length);
//$(".fancybox-slide").append($('#'+index).html());
},

Trouble clearing object from array using buttons (jquery)

I'm attempting to move an image and data-id attribute from one section of divs, to a placeholder section of divs. I also want to be able to splice out those objects from the array when clicking the 'remove' button from either section.
It's mostly working by targeting the 'data-id' attribute and then performing the actions I want it to - but I'm running into one bug.
https://jsfiddle.net/kgmucdac/
$(document).ready(function() {
var selections = [];
var prodLength = 4;
var arrayVal = "";
$(".killThis").click(function() {
killCount();
});
$("#products").on('click', '.add', function () {
$(this).removeClass('add');
$(this).addClass('removeTop');
$(this).text("remove");
$('.remove').show();
arrayVal = ($(this).data('id'));
if (selections.length <= prodLength) {
selections.push({src: $(this).parent().find('img').attr('src'),vid: $(this).data('id')});
}
addProd();
console.table(selections);
});
$("#products").on('click', '.removeTop', function () {
arrayVal = ($(this).data('id'));
$(this).removeClass('removeTop');
$(this).addClass('add');
$(this).text("add");
nukeProd();
cleanArray();
drawProds();
});
$('#placeholders').on('click', '.remove', function () {
arrayVal = ($(this).data('id'));
console.log(arrayVal);
nukeProdReverse();
cleanArray();
tempClear();
drawProds();
})
function drawProds() {
var prods = $('#placeholders').find('.placeholder');
for (var i = 0; i < prods.length; i++) {
var prod = prods[i];
var selection = selections[i];
if ((selection != undefined)) {
$(prod).find('img').attr('src', selection.src);
$(prod).find('.remove').attr('data-id', selection.vid)
} else {
$(prod).find('img').attr({
'src': 'https://i.imgur.com/D6MQP01.png'
});
$(prod).find('.remove').css('display', 'none');
}
}
}
function addProd() {
drawProds();
}
function nukeProd() {
$('.placeholder[data-id="' + arrayVal + '"]').find('img').attr({
'src': 'https://i.imgur.com/D6MQP01.png'
});
$('.remove[data-id="' + arrayVal + '"]').attr('data-id', '');
}
function cleanArray() {
for(var i = 0; i < selections.length; i++) {
if(selections[i].vid == arrayVal) {
selections.splice(i, 1);
break;
}
}
console.table(selections);
}
function nukeProdReverse() {
$('.placeholder[data-id="' + arrayVal + '"]').find('img').attr({
'src': 'https://i.imgur.com/D6MQP01.png'
});
$('.remove[data-id="' + arrayVal + '"]').removeAttr('data-id');
$('.removeTop[data-id="' + arrayVal + '"]').text("add");
$('.removeTop[data-id="' + arrayVal + '"]').addClass('add');
$('.removeTop[data-id="' + arrayVal + '"]').removeClass('removeTop');
}
function tempClear() {
$('.remove').removeAttr('data-id');
}
function killCount() {
console.log(arrayVal);
}
});
That's my JSFiddle that I've been working on. When I add the products in any order from the top row, I can delete them using the top row's remove buttons, no issues.
However, using the bottom row's 'remove' buttons, I can only remove them all if I start from right to left (4th, 3rd, 2nd, 1st)... If I remove them in any other order, e.g., the 3rd, the one that slides into its place will not work correctly.
I think it has something to do with the index incrementation but I'm kind of at the end of my road on this in terms of what I know how to do/cobble together.

Change images randomly on click without repeating

I found this code on Stack Overflow: change images on click.
And it works for me. I want it to be random, but how can i prevent it from repeating the images. It should first repeat the images, when the user has clicked through all images.
I have made an JSfiddle with my code: http://jsfiddle.net/gr3f4hp1/
JQuery code:
var images = ["02.jpg","03.jpg","01.jpg"];
$(function() {
$('.change').click(function(e) {
var image = images[Math.floor(Math.random()*images.length)];
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
});
});
});
Keep track of the numbers that you have generated, and if its a repeat then get a new number.
You can Work Around This
var usedImages = {};
var usedImagesCount = 0;
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]){
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
you can try this code .
var images = ["02.jpg","03.jpg","01.jpg"];
var imagecon = [];
$(function() {
$('.change').click(function(e) {
if(images.length == 0) { // if no image left
images = imagecon; // put all used image back
imagecon = []; // empty the container
}
var index = Math.floor(Math.random()*images.length);
var image = images[index];
imagecon.push(image); // add used image
images.splice(index,1); // remove it to images
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
});
});
});
you could add a class to every image that appears like:
image.addClass("viewed")
and write an if statement that show the image only if it hasn't the class viewed:
if(!image.hasClass(viewed)){
(show the image methods);
image.addClass("viewed")
}
I'm not going to make all the code for you, just try this way, learn, fail, success, have fun! :D
Try this image change according to imgCnt variable.
var images = ["01.jpg","02.jpg","03.jpg","01.jpg"];
var imgCnt=1;
$(function() {
$('.change').click(function(e) {
// var image = images[Math.floor(Math.random()*images.length)];
if(imgCnt >= images.length){
imgCnt=0;
}
var image =images[imgCnt];
// alert(image);
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
imgCnt++;
});
});
});
Demo
There are lots of method here i just push the value of visited image in to Visited array
Campate two array show only differ element
var images = ["02.jpg","03.jpg","01.jpg"];
var visited = [];
$(function() {
$('.change').click(function(e) {
var image = images[Math.floor(Math.random()*images.length)];
visited.push(image);
$('#bg').parent().fadeOut(200, function() {
y = jQuery.grep(images, function(value) {
if(jQuery.inArray(value, visited) == -1){
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
}
});
} });
});
});
I hopes its help

Prevent drag and drop on captions

the hosting company loads a script on all their sites that is allowing for the tabs to be dragged/dropped , however it is also causing the caption images within the same body_home page to be drag/drop , i have requested this be fixed but i don't think they are concerned.
I am permitted to load my own jquery, javascript , html ,css onto the site to do changes , but i can not stop the host from loading this js file , so how can i reverse this ? Here is a snippet of the portion of the js file i think that is causing this problem .
I am permitted to load my own footer and header messages , so is there anyway i can remove what they are doing here , or reverse the effect on the captions ?
i cant find a way for the listener to be removed from outside.
They have used an anonymous function on the event 'domready' .
Does javascript have a feature to remove the listener from outside the anonymous method
window.onload=function() {
if (document.getElementById("body_home")) {
set_up_double_click_events();
if (document.getElementById("homepagetabs") && document.getElementById("tab2")) {
new Sortables($('homepagetabs'), {
onComplete: function() {
var parent = this.element.parentNode;
var saveIt = false;
if (typeof currentTabOrder == "undefined") {
currentTabOrder = new Array();
for (var i = 0; i < parent.getChildren().length; i++) {
currentTabOrder[i] = i;
}
}
for (var i = 0; i < parent.getChildren().length; i++) {
var seqno = parent.getChildren()[i].id.substr("tab".length);
if (currentTabOrder[i] != seqno) {
saveIt = true;
currentTabOrder[i] = seqno;
}
}
if (saveIt) {
var url = window.location.protocol + "//" + window.location.host + "/" + year + "/save_setting?L=" + league_id + "&TITLE=TABORDER&VALUE=" + currentTabOrder.join();
makeHttpRequest(url);
}
}
});
}
window.addEvent('domready', function() {
new Sortables('.homepagemodule CAPTION', {
clone: true,
revert: true,
opacity: 0.7,
onStart: function() {
dndMovingModule = this.element.parentNode.parentNode.id.toUpperCase();
},
onComplete: function() {
dndDroppedOntoModule = this.element.parentNode.parentNode.id.toUpperCase();
if (typeof dndMovingModule != "undefined" && typeof dndDroppedOntoModule != "undefined" && dndMovingModule != dndDroppedOntoModule) {
var url = window.location.protocol + "//" + window.location.host + "/" + year + "/save_setting?L=" + league_id + "&TITLE=MODULE&VALUE=" + dndMovingModule + "," + dndDroppedOntoModule;
// alert("calling: " + url);
makeHttpRequest(url);
setTimeout("window.location.reload();", 250);
}
}
});
});
}
}
$(document).ready(function() {
$('#DIVID').on('mousedown', function(e) {
return false;
});
});
I would put an HTML class attribute on all of your images that are producing the problem. Obviously, jQuery uses CSS style selectors. See the following example.
$(function(){
$('.ElementClass').mousedown(function(){
return false;
});
});
When you return false; onmousedown it prevents the default behavior in most Browsers, which is to grab the image so the Client can drop and drag the image into into a new tab or window to view it with their Browser.

Fill ProgressBar by value/width of other ProgressBars

I am generating first four buttons and progress bar dynamically(Java,CPP,Csharp & functional). I am adding width/value to them using javascript/jquery. Now i want to add width/value of all those progress bar to mainProgreeBar after clicking on finish button. Here is my JavaScript code, and Here is FIDDLEabout same
JS
function showSummery(){
$("#summeryDiv").show();
var finalScore= 0;
$( "#subjdiv" ).next( ".btn",function(){
var a = $(".btn").val();
finalScore =parseInt($('#Javaprogressbar').val());
});
// finalScore = finalScore +$( "#subjdiv" )
// .nextUntil( '.progress-bar', 'div')
// .width();
alert(finalScore);
$('#mainProgressBar').css(
"width",finalScore+"%"
);
document.getElementById('#mainProgressBar').innerHTML=finalScore+"%";
}
function showSummery(){
var inputValues;
$('.final').each(function() {
var type = $(this).attr("value");
inputValues = inputValues + type;
})
alert(inputValues);
$('#mainProgressBar').css("width",inputValues+"%");
}
This is working for me

Categories

Resources