Load different content in FancyBox2 based on table cell index - javascript

I have a table that shows presentations and their times. When a cell is clicked, it brings up a FancyBox with the presentation's title, description, and the speakers. The former two items are static, but the latter changes based on the time the presentation is being held.
What I'm trying to figure out is how to change the content of the same FancyBox depending on which table cell was clicked. The number of cells is known. I got up to getting the index of the cell, but not sure where to go from here.
Full page: https://secure.michebag.com/static/elevate-breakout/elevate-breakout.html
jQuery:
$(document).ready(function(){
// Get table cell index
// Assign dynamic content
$('table tr:first td:eq(1)').click(function(){
// What goes here?
});
});

EDIT: Since we're talking about static content, my post is long and useless. The gist of the problem is still how you introduce the information to your code - I would create some objects to describe what you want to add, identifying different meetings/talks with their hrefs. Since it's static content, you only need to do this once(as the page loads) - no need for any fancy click handlers and the like.
Sample code:
var meetings = {
"#pwap" : { color: "dark-pink", speakers: [ "Speaker Guy", "Speaker Girl" ] }
// And so on
}
// Then simply loop over the meetings and do your work over each one.
for (var href in meetings) {
// Color
var meeting = meetings[href];
$('a[href=' + href + ']').parent().addClass(meeting.color);
// Add speakers
var element = $(href);
var speakers = meeting.speakers;
for (var i = 0, length = speakers.length; i < length; i++) {
// Add each speaker as a paragraph with his name.
$('<p>').text(speakers[i]).appendTo(element);
}
}

Related

Appending to div puts first item at bottom, and rest in correct order

I am trying to add items into a div by appending to the end of the div during a for loop. The idea being I have records from a database with a "Total score" field, and I want the highest-scoring records on top.
The container div where I want to put the elements is this:
<div id="fetch-n-sites-output"></div>
And my callback function upon a successful AJAX call is as follows:
function updateNSites(data){
$("#fetch-n-sites-output").empty();
data["fetched-sites"].map(function(element, index){
var cloned = cloneTemplate(index, element);
console.log(`Processing site ${index}...`);
$("#fetch-n-sites-output").append(cloned);
});
}
For completeness, my cloneTemplate function is this:
function cloneTemplate(index, data){
// CLONE TEMPLATE
var template = $("#test-template").html().trim();
var clone = $(template);
var siteID = data["site_id"];
var totalSiteScore = data["total_site_score"];
// UPDATE CLONE WITH SITE-SPECIFIC INFORMATION
// 0. Update ID of div element with site id
var mainDiv = $("div.greendiv").eq(index);
mainDiv.attr("id", `site-${siteID}`);
// 1. Update header with "Site ID: {site_id}"
$(`#site-${siteID} > div.reddiv > p.header-text`).text(`Site ID: ${siteID} - Total Score: ${totalSiteScore}`);
// 2. Add event handlers
// $(`#site-${siteID} div.site-sidenav`).on("click", 'a', function() {
// alert("clicky");
// });
$(`#site-${siteID}`).find(".site-navlink").on("click", function () {
alert("clicky");
});
// SHOW CLONE
clone.removeClass("template-hidden").addClass("template-show");
return clone;
}
When I retrieve 3 sites, the highest scoring site is always at the bottom. This doesn't make sense to me, because my SQL query orders by this total site score. The highest scoring site is always placed at the bottom, but the other sites are ordered properly:
Another odd problem (which I think is related to this main issue) is that the event handlers that I add in the cloneTemplate function to handle clicks on the <a> tags (right now just calls an alert() for testing) only work on the elements other than the first:
Whereas clicking 'GENERAL' on the first element does not trigger an alert. Could someone please help me figure out why every added element but the first behaves properly, but the first does not? And why the first element is always getting placed at the bottom? Thank you

Not able to identify element display values

I have photo gallery type of web page. It is comprised of grid of photo thumbnails, with assigned tags beneath them.
At top of page is a list of all of the tags, formatted as buttons. User can click on one or more tag buttons to filter photos. I am using Isotope js for this filtering. This works fine.
However I want to add new feature that runs after the Isotope filtering that will hide any tag buttons that are not assigned to any of the remaining filtered photos.
My plan was to do following:
identify all visible photos
create array from visible photos' tags
use array to hide any unmatched tags
However, I am having problems identifying visible photos after I click tag buttons and Isotope does its filtering.
It seemed like it would be quite straightforward. Isotope js changes a specified element's display = "none" for the hidden photos. Eg if I inspect the element, I can see hidden elements have display = "none"
I created a 'visibletags' function that is called at end of tag button on click to find elements where display != "none":
$('.filter-button').on('click', function() {
// isotope code here
// isotope hides some photos setting their div's `display = "none"`
visibletags();
}
function visibletags(){
var imgdivs = document.querySelectorAll('.imgdiv');
var showtags = [];
for (var i=0, max=imgdivs.length; i < max; i++) {
if (window.getComputedStyle(imgdivs[i]).display != "none") {
// this should be a div that is not hidden by Isotope js
// so loop through it's tags to build array
// array will be used later to hide unmatched tags
var phototagspans = imgdivs[i].querySelectorAll('.photo-tag');
for (var j=0, max=phototagspans.length; j < max; j++) {
showtags.push(phototagspans[j].className);
}
}
}
}
But I am not able to identify the element's display value. I have tried using window.getComputedStyle(imgdivs[i]).display, imgdivs[i].display and imgdivs[i].style.display
Edited to modify question:
I tested running the 'visibletags()' function as another button on click event that I manually click after the isotope filtering is complete. This successfully gets all photo element display values. So that part of code does work.
So my question now is how to run 'visibletags()' function after the Isotope filtering in a way that it is one complete set of code?
I tried changing the 'visibletags()' function to run as $('.filter-button').mouseup(function() but didn't get filtering results.
Maybe this is now general Javascript question eg how to get on click event's results after they have been rendered?
I'm not familiar with Isotope, but you probably need to use a callback function. Check out this documentation, especially the layoutComplete part: https://isotope.metafizzy.co/events.html
In your case, the result could be something like this:
$('.filter-button').on('click', function() {
// initialize isotope
$isotope.on('layoutComplete', function() {
visibletags();
});
// other isotope code here
}

Change Text of Array Of links in jQuery

For my school's website they have a dropdown list of courses that you're currently enrolled in on the home page. However, if you see it, it is cluttered full of letters that many people might not want to see.
I already know how I'm going to do this. I'm going to use jQuery to select each list item:
var links = $(".d2l-datalist li .d2l-course-selector-item .d2l-left .vui-link");
This returns an array of <a> elements in text form.
Using links.text("Boo!"); I can set the text of all of them to "Boo!", but I want to change each one individually, using a for/in loop to itterate through each <a> and change the text depending on what the value of the href is.
However, whenever I do this, since the items in the array are strings, I cannot do anything to them with jQuery.
Any help with this is appreciated :)
Here's my code so far (running from a $.getScript() from a JS bookmarklet):
var links = $(".d2l-datalist li .d2l-course-selector-item .d2l-left .vui-link");
//links.text("Boo!");
var count = 1;
for (var link in links) {
link.text("Boo #" + count);
count += 1;
}
Relevant markup: http://hastebin.com/ulijefiqaz.scala
You can use the jQuery .each iterator function.
var links = $(".d2l-datalist li .d2l-course-selector-item .d2l-left .vui-link");
var count = 1;
links.each(function() {
$(this).text("Boo #" + count++);
});

Dynamically create numerous methods in jQuery?

A number is generated on my page in a hidden text field based on a number of 'pages' that need to be produced.
The plan is to dynamically allow the user to switch between the pages by clicking on numbers (e.g. if we have 3 pages, they can click on 1, 2 or 3 to display each page).
The problem is that the number of pages will vary from run to run, but in order for me to be able to add the page switching functionality in js/jQuery, I need to create a .click() method for each page button.
However because the number of pages isn't a set amount, I need to somehow create these methods dynamically - creating as many as are required, so a .click() function for each page.
$("#page1" ).click(function() {
for(var i = 0; i < tableCount; i++){
$("#usertable" + (i)).hide();
}
$("#usertable1").show();
});
Above is an example of a simple function I wrote that will be executed when the 1st page button is pressed and it iterates through all pages, hides them and then shows the 1st page. However if I have 5 pages, I need to somehow dynamically create a $("#page2" ).click() function and a $("#page3" ).click() function and so on.
Any ideas?
You can use attribute begins with selector
$("[id^=page]").click(function () {
// do stuff
var id = this.id.slice(-1);
for (var i = 0; i < tableCount; i++){
$("#usertable" + i).not("[id$=" id "]").hide();
}
$("#usertable" + id).show();
})
Use of common classes and some attributes will help
<a class="page-link" href="#page1">Page 1</a>
<div id="page1" class="page-content"></div>
Then one click handler works for whole class of links. Within any jQuery event handler this is the element the event occured on
$('.page-link').click(function(){
// hide whole class of content , filter for the one to show
$('.page-content').hide().filter(this.hash).show();
});
Or a bit more verbose for understanding
$('.page-link').click(function(){
var idSelector = $(this).attr('href'); // "#page1"
$('.page-content').hide().filter(idSelector).show();
});

How to stop a HTML element fading out using Javascript?

UPDATE
I have a jsfiddle showing the issue here: http://jsfiddle.net/waf11s6u/1/ When you type a letter into the search bar, the custom scrollbar attached to the div disappears. The scrollbar may be getting faded out by the code that fades out non-matching words from the div?
~~
I’m creating a custom multi-friend selector for a Facebook game, it looks similar to this: http://tinyurl.com/gus79cf
The user can type into a search bar and any matching friend names appear in the area below.
I’m using a custom scrollbar plugin to design the scrollbar for scrolling down through the list of friends.
This is the plugin’s site: http://manos.malihu.gr/jquery-custom-content-scroller/
Visually the scrollbar is made up of two parts, the first is the track (I’ve drawn the track onto the background image, so it’s not actually part of the Javascript code), and the second part is the icon, the icon is the small image that moves up and down along the track.
The scrollbar works perfectly (meaning that the icon slides up and down correctly), except for one thing, whenever the user types a letter into the search bar the icon disappears, and it only becomes visible again when the search bar is empty.
The div which contains the names & images of friends is created dynamically in Javascript (it's called "mfsForm"). When the user begins typing a name, I have some Javascript that will fade out non-matching friend names & images.
I think that this code is also causing the icon to disappear.
This is the code in question:
// Earlier code here connects to Facebook's API.
// Then get the list of friends for this user with the Graph API
FB.api('/me/invitable_friends?limit=48', function(response) {
var container = document.getElementById('mfs');
// Creating the div "mfsForm" (this will hold the friend names & photos, and is also what the custom scrollbar is applied to.)
var mfsForm = document.createElement('form');
mfsForm.id = 'mfsForm';
mfsForm.className = " mCustomScrollbar mfsForm";
// Iterate through the array of friends object and create a checkbox for each one.
for (var i = 0; i < response.data.length; i++) { //Math.min(response.data.length, 10)
var friendItem = document.createElement('div');
friendItem.id = 'friend_' + response.data[i].id;
friendItem.style.cssText="width:100px; height:100px; padding:7px; color:#FFF;"
friendItem.style.cssFloat="left";
friendItem.innerHTML = '<input type="checkbox" name="friends" value="' + response.data[i].id + '" />';
var img = document.createElement('img');
img.src = response.data[i].picture.data.url;
img.style.cssText = 'width: 70px;height: 70px;'
friendItem.appendChild(img);
var labelName = document.createElement('label');
labelName.style.cssText = 'font-size: 14px;'
labelName.innerHTML = response.data[i].name;
friendItem.appendChild(labelName);
mfsForm.appendChild(friendItem);
}
container.appendChild(mfsForm);
console.log(mfsForm);
$(mfsForm).mCustomScrollbar();
// Create a button to send the Request(s)
var sendButton = document.createElement('div');
sendButton.id = 'sendButton';
sendButton.onclick = sendRequest;
container.appendChild(sendButton);
$("#filter").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = $(this).val()//, count = 0;
// Loop through the comment list
$("#mfsForm div").each(function(){
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut("slow");
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
//Attempting to fade in the icon here:
$(this).next('.mCSB_dragger_bar').fadeIn("slow");
}
});
})
});
I think that $(this).fadeOut("slow"); is making the scrollbar icon fade out. I've tried to target the icon by referencing its class (mCSB_dragger_bar) and fading it in here:
$(this).next('.mCSB_dragger_bar').fadeIn("slow"); but it's not working.
Any help or suggestions on what I could try to fix this problem would be really appreciated, thank you in advance!
What is the problem?
You do not show normal code to see where your script delete icon and i can say you to force your script to display this icon.
Put to input the code onchange="f()" or onkey pres or other.
And
<script>
function f(){ //$('#icon') the element witch contain icon that disapear
$('#icon').css('visibility','visible').css('display','block');
$('#icon').attr('background','url('/icon.png')')}`
/*$('#parent-of-icon').appendChild(icon );*/
And other depend why the icon disapear.
May be your script delete the icon (html element) then create it.
In this mode the icon will always appear on each key press.
Try $(this).find('.mCSB_dragger_bar').fadeIn("slow"); not $(this).next('.mCSB_dragger_bar').fadeIn("slow");
If element with class name mCSB_dragger_bar exist on $(this) element ( $this -> $("#mfsForm div") -> some div's on element with id=mfsForm) it will find it and show;
NEXT return only one element after $this, may be between $(this) and mCSB_dragger_bar exist another element.
Also try $(this).parent().find('.mCSB_dragger_bar').fadeIn("slow"); if mCSB_dragger_bar and $(this) is on the same doom level

Categories