How can I make my script work with an array? - javascript

This Javascript controls a Monial Content box with forward and back buttons to move forwards or backwards but it only works for 2 DIVs, how can I make this script work with an array so I can add more elements?
e.g.
Current Script Diagram
The Script Code
$(document).ready(function(e) {
showQuote();
$(".left").click(function(e) {
$("#monial_btn_1").trigger("click");
});
$(".right").click(function(e) {
$("#monial_btn_2").trigger("click");
});
$("#monial_btn_1").click(function(e) {
$(".monial_content_1").fadeIn("fast");
$(".monial_content_2").fadeOut("fast");
var obj=$(this);
obj.removeClass();
obj.addClass("monial_btn_selected");
obj=$("#monial_btn_2");
obj.removeClass();
obj.addClass("monial_btn");
});
$("#monial_btn_2").click(function(e) {
$(".monial_content_1").fadeOut("fast");
$(".monial_content_2").fadeIn("fast");
var obj=$(this);
obj.removeClass();
obj.addClass("monial_btn_selected");
obj=$("#monial_btn_1");
obj.removeClass();
obj.addClass("monial_btn");
});

var n = 10
for(i = 1; i < n; i++) {
$("#monial_btn_" + i).click(function(e) {
$(".monial_content_" + i).fadeIn("fast");
$(".monial_content_" + (i + 1)).fadeOut("fast");
var obj=$(this);
obj.removeClass();
obj.addClass("monial_btn_selected");
obj=$("#monial_btn_" + (i + 1));
obj.removeClass();
obj.addClass("monial_btn");
});
}

Related

Lightbox Jquery on click next image

I am using a mixture of freewall and featherlight plugins to produce a responsive gallery which opens into a lightbox, however, I am having the following issue with trying to get the lightbox to switch to the next image (i + 1) when clicked.
The Lightbox image code enter image description here. What I want to do is to change the img src to i + 1 so it will go to the next image on click.
I also have this project on Github which might help understand: https://github.com/adamianniello/adamianniello.com/blob/master/B%C3%A6b%C3%A6l%C9%99n_Pasadena.html
<script type="text/javascript">
var temp = "<div class='brick' style='width:{width}px;'><a href='#' data-featherlight='i/jpl/{link}.jpg'><img src='i/jpl/{index}.jpg' width='100%'></a></div>";
var w = 1, h = 1, html = '', limitItem = 54;
for (var i = 0; i < limitItem; ++i) {
w = 1 + 3 * Math.random() << 0;
html += temp.replace(/\{width\}/g, w*150).replace("{index}", i + 1).replace("{link}",i + 1);
}
$("#freewall").html(html);
var wall = new Freewall("#freewall");
wall.reset({
selector: '.brick',
animate: true,
cellW: 150,
cellH: 'auto',
onResize: function() {
wall.fitWidth();
}
});
var images = wall.container.find('.brick');
images.find('img').load(function() {
wall.fitWidth();
});
<div id="freewall" class="free-wall"></div>
You have to manually trigger the next element on click on the image. Just do something like below
A function to trigger featherlight to show next image. I had assumed you initialize featherlite using .brick a css selector. Feel free to change this to your desired one. This function builds your next a tags data-featherlight and calls featherlight over it.
function showNextImage(i) {
$('.brick a').featherlight('i/jpl/' + (((i +1) % (limitItem + 1))) + '.jpg');
}
Add a onclick in your div to call the function with current i.
var temp = "<div class='brick' style='width:{width}px;' onclick='showNextImage({index})'> <a href='#' data-featherlight='i/jpl/{link}.jpg'><img src='i/jpl/{index}.jpg' width='100%'></a></div>";
var w = 1, h = 1, html = '', limitItem = 54;
for (var i = 0; i < limitItem; ++i) {
w = 1 + 3 * Math.random() << 0;
html += temp.replace(/\{width\}/g, w*150).replace("/\{index\}/g", i + 1).replace("{link}",i + 1);
}
$("#freewall").html(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.

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.

jquery hover and selected issue

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; });
});

Cannot access objects in associative arrays using jQuery

I am trying to create and array of objects so that I can access them in a for loop in jQuery and I know that this works in Actionscript so what I am trying to do is convert my current knowledge to jQuery that will work.
Please have a look at this and tell me why I cannot access divToShow
Thanks guys
var homeImages = new Array();
homeImages[0] = { hoverImage: ".leftColImage1", divToShow: ".image1", rollOverImg: "img-family-over.jpg" };
homeImages[1] = { hoverImage: ".leftColImage2", divToShow: ".image2", rollOverImg: "img-students-over.jpg" };
homeImages[2] = { hoverImage: ".leftColImage3", divToShow: ".image3", rollOverImg: "img-pros-over.jpg" };
homeImages[3] = { hoverImage: ".leftColImage4", divToShow: ".image4", rollOverImg: "img-retired-over.jpg" };
var hoverImage;
var activeDiv;
var mainContent = ".mainContent";
for (k = 0; k < homeImages.length; k++) {
homeImages[k].id = k;
$(homeImages[k].hoverImage).mouseover(function() {
//alert("divToShow : " + homeImages[this.id].divToShow);
alert("this : " + this.id);
activeDiv = homeImages[k].divToShow;
$(".leftColImage1 img").attr("src", "/App_Themes/MyChoice2010/Images/" + homeImages[k].rollOverImg);
$(mainContent).hide();
$(homeImages[k].divToShow).slideDown("slow");
}).mouseout(function() {
$(".leftColImage1 img").attr("src", "/App_Themes/MyChoice2010/Images/img-family.jpg");
$(".image1").hide();
$(mainContent).slideDown("slow");
});
}
Ok, try this:
for (k = 0; k < homeImages.length; k++) {
(function(current) {
$(current.hoverImage).hover(function() {
activeDiv = current.divToShow;
$(".leftColImage1 img").attr("src", "/App_Themes/MyChoice2010/Images/" + current.rollOverImg);
$(mainContent).hide();
$(current.divToShow).slideDown("slow");
},
function() {
$(".leftColImage1 img").attr("src", "/App_Themes/MyChoice2010/Images/img-family.jpg");
$(".image1").hide();
$(mainContent).slideDown("slow");
});
})(homeImages[k]);
}
Or alternatively:
function setUpHover(item) {
$(item.hoverImage).hover(function() {
activeDiv = item.divToShow;
$(".leftColImage1 img").attr("src", "/App_Themes/MyChoice2010/Images/" + current.rollOverImg);
$(mainContent).hide();
$(item.divToShow).slideDown("slow");
},
function() {
$(".leftColImage1 img").attr("src", "/App_Themes/MyChoice2010/Images/img-family.jpg");
$(".image1").hide();
$(mainContent).slideDown("slow");
});
}
for (k = 0; k < homeImages.length; k++) {
setUpHover(homeImages[k]);
}
//alert("divToShow : " + homeImages[this.id].divToShow);
In that context, this refers to the current HTML element, not the current homeImages element.
You are accessing the variable k from inside the mouseover handler function. But by the time that function is called, the value of k has already changed and is now equal to homeImages.length since the for loop has already run to completion.
One way to solve this is to use $.each instead of the for loop:
$.each(homeImages, function(k, element) {
element.id = k;
$(element.hoverImage).mouseOver(function() {
.... //you can use the value of k or element here
});
});
This will work because the function passed to $.each creates a new closure which remembers the value of k for each iteration.
The reason is the old classic relating to closures: in the mouseover handler, k is always set to its last value of 4 rather than its value when the mouseover handler was created, which is what your code is expecting.
You can fix this by creating the mouseover handler in a function:
function addMouseEventHandlers(imageIndex) {
var homeImage = homeImages[imageIndex];
homeImage.id = imageIndex;
$(homeImage.hoverImage).mouseover(function() {
//alert("divToShow : " + homeImages[this.id].divToShow);
alert("this : " + this.id);
activeDiv = homeImage.divToShow;
$(".leftColImage1 img").attr("src", "/App_Themes/MyChoice2010/Images/" + homeImage.rollOverImg);
$(mainContent).hide();
$(homeImage.divToShow).slideDown("slow");
}).mouseout(function() {
$(".leftColImage1 img").attr("src", "/App_Themes/MyChoice2010/Images/img-family.jpg");
$(".image1").hide();
$(mainContent).slideDown("slow");
});
}
for (k = 0; k < homeImages.length; k++) {
addMouseEventHandlers(k);
}

Categories

Resources