Trouble clearing object from array using buttons (jquery) - javascript

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.

Related

Mouse actions possible on all id tags on a webpage

What I want to do is, find all possible actions (click , hover, etc) on each element id on a web page.
Below is my effort towards it:
function executeInteractions($) {
for (var interaction_count = 0; interaction_count < interactions.length; interaction_count++) {
var obj = interactions[interaction_count];
for (var event_count = 0; event_count < obj.events.length; event_count++) {
(function(elem, event_name, e_count, i_count, t_i_count) {
setTimeout(function() {
elem.trigger(event_name);
var sendData = {id : elem.attr('id') , event_n: event_name }
&.post("link#",sendData)
setTimeout(function() {
}
}, 10);
if (i_count + 1 >= t_i_count) {
window.interactionsComplete = true;
}
}, 500 * i_count);
}(obj.item, obj.events[event_count], event_count, interaction_count, interactions.length));
}
}
}
function findInteractions($) {
$(document).click(function(e) {
e.preventDefault();
});
$(document).submit(function(e) {
e.preventDefault();
});
var node, toBeProcessed = new Array;
toBeProcessed.push($('body')[0]);
while (toBeProcessed.length) {
node = $(toBeProcessed.pop());
var eventObject = node.data('events');
if (eventObject) {
var events = [];
for (var e in eventObject) {
events.push(e);
}
interactions.push({
'item': node,
'events': events
});
}
var childrens = node.children();
if (childrens && childrens.length > 0) {
for (var i = 0; i < childrens.length; ++i) {
toBeProcessed.push(childrens[i]);
}
}
}
}
window.interactions = [];
When the post request is received at the server end, I get lot of null values for id.
Can someone help me out here, or may be suggest any other efficient method to capture all possible actions on id elements on a web page.
You can apply unique class to each attribute on page and then write .click()/.mouseover() JQuery event on it.
HTML:
<p class="uniqueClass">1st para</p>
<p class="uniqueClass">2nd para</p>
JQuery code:
<script>
$( ".uniqueClass" ).click(function() {
alert("Clicked");
});
</script>
For mouse over, you can use .mouseover() function like:
<script>
$( ".uniqueClass" ).mouseover(function() {
alert("Mouse Over");
});
</script>

How to display only one image in ezpublish JS slider

I'm a beginner php developer, and have a shockingly poor fluency in Javascript. An ezpublish website I'm working on has this slider in as a default piece of code, but it displays three items. How can I edit it to show only 1 item? The code is:
(function() {
YUI( YUI3_config ).use( 'node', 'event', 'io-ez', function(Y, result) {
Y.on('domready', function(e) {
var offset = 0;
var limit = 1;
var total = {$block.valid_nodes|count()};
var handleRequest = function(e) {
var className = e.target.get('className');
if ( className == 'carousel-next-button' ) {
offset += 1;
if ( offset > total )
offset = 0;
}
if ( className == 'carousel-prev-button' ) {
var diff = total - offset;
if( offset == 0 )
offset = 0;
else
offset -= 1;
}
var colContent = Y.Node.all('#block-3 .col-content');
colContent.each(function(n, e) {
n.addClass('loading');
var height = n.get('region').bottom - n.get('region').top;
n.setStyle('height', height + 'px');
n.set('innerHTML', '');
});
var data = 'http_accept=json&offset=' + offset;
data += '&limit=' + limit;
data += '&block_id={$block.id}';
Y.io.ez( 'ezflow::getvaliditems', { on: { success: _callBack
}, method: 'POST', data: data } );
};
var _callBack = function(id, o) {
if ( o.responseJSON !== undefined ) {
var response = o.responseJSON;
var colContent = Y.Node.all('#block-{$block.id} .col-content');
for(var i = 0; i < colContent.size(); i++) {
var colNode = colContent.item(i);
if ( response.content[i] !== undefined )
colNode.set('innerHTML', response.content[i] );
}
}
};
var prevButton = Y.one('#block-{$block.id} input.carousel-prev-button');
prevButton.on('click', handleRequest);
var nextButton = Y.one('#block-{$block.id} input.carousel-next-button');
nextButton.on('click', handleRequest);
});
});
})();
</script>
A hand with this would be great x
Looks to me like this code loads each item after the user clicks prevButton or nextButton. So the simplest way to force only a single item to display is probably to hide those buttons.
Without the markup it's hard to say what the optimal solution is, but I would try to find out what makes the particular markup you're working with into a carousel (I'd guess a class containing "carousel") and remove that so that it's just a single item without the carousel functionality.
For what it's worth, this question is not specific to eZ Publish or PHP so I'd consider removing those tags.

How can I make my script work with an array?

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

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