Getting different variables using .each while using one simple script - javascript

I am trying to get a link from some youtube embedded video's, in order to make some links to them, which in their place trigger a nice fancybox to watch the video in.
Getting the ID from the embedded video, and replacing it in the right link isnt the problem. It gets dirty as soon as I try to code in the loop.
The javascript I use is as following:
$('.portfolio_det iframe').each(function(i) {
var videolink = this.src.replace('http://www.youtube.com/embed/', '');
var videolink = videolink.replace('?fs=1&feature=oembed', '')
$('.portfolio_thumb .youtubeLink').each(function(i) {
$(this).attr('href', "http://www.youtube.com/watch?v=" + videolink);
});
});
The Last piece of the code retrieves the link in
Though they all get the href created on the first youtube video.
How do I set the variable to be in the loop aswell?
To make it all a bit clearer, here is a jsfiddle from the setup:
JS fiddle

You are defining var videolink twice and leaving the ; off of the end of the second one.
The second line should be:
videolink = videolink.replace('?fs=1&feature=oembed', '');

Define the variable outside the loop. Also once if you have defined a variable you dont have to put var in front of it.
var videolink;
$('.portfolio_det iframe').each(function(i) {
videolink = this.src.replace('http://www.youtube.com/embed/', '');
videolink = videolink.replace('?fs=1&feature=oembed', '')
$('.portfolio_thumb .youtubeLink').each(function(i) {
$(this).attr('href', "http://www.youtube.com/watch?v=" + videolink);
});
});

Related

Change thousands sign using JS

Here I would like to replace in the draggable slider the "," sign used for the thousands into this sign " ' " (a quote mark).
I am currently using a plugin to render the table (from a JSON file) so I cannot alter the HTML.
I am able to change the sign, in fact on page load the sign seems correct, but as soon I drag the slider the separator changes to a comma again.
I saw that the data is rendered from the Plugin with a comma in the aria-valuetext="" attribute: <div class="noUi-handle noUi-handle-upper" data-handle="1" tabindex="0" role="slider" aria-orientation="horizontal" aria-valuemin="0.0" aria-valuemax="100.0" aria-valuenow="100.0" aria-valuetext="2,290.00"><div class="noUi-tooltip">2,290.00</div></div>
I tried using this code without any results:
<script>
window.onload = function(){
var div = document.querySelectorAll('.noUi-tooltip');
div.forEach(function(r) {
var text = r.textContent;
var output = text.replace(/[,|]/g, "'");
r.innerHTML = output;
});
}
</script>
What am I writing wrong?
I am using WordPress and the wpdatatables plugin.
I'm not sure about the plugin you've used for your slider but perhaps you can try this for now:
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type == "attributes") {
var parentEl = document.getElementsByClassName('noUi-handle-upper');
var childEl = parentEl.childNodes[0];
childEl.innerHTML = childEl.innerHTML.replace(',', '\'');
}
});
});
observer.observe(document.getElementsByClassName('noUi-handle-upper')[0], {
attributes: true,
});
It's using MutationObserver which is not supported by older browsers. You can read more about it at https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver.
This is because you modify the string just in the beginning (on load).
This is why the code works in the beginning but doesn't work later, because it runs once and then stops.
I don't know how to use WordPress or sliders, but I'd advise you to use an 'on value changed' command, so the text will change to whatever you want it to each time the slider's value is changed.
I will post this now but I'll review your code and will try to update this with more exact information later.

How do I get the title attribute as a variable to replace the hashtag in prettyPhoto?

I'm trying to replace the hashtag link of an expanded image with its title, rather than a numbered index.
I've managed to remove the unwanted numbering from the url but I don't know how to retrieve the title.
While editing the prettyPhoto javascript I've changed the SetHashtag function to this:
function setHashtag(){
var title = pp_titles;
if(typeof theRel == 'undefined') return; // theRel is set on normal calls, it's impossible to deeplink using the API
location.hash = theRel + '/'+title+'/';
};
Using 'pp_titles' in the variable though seems to pull all the titles from the whole gallery and add them to the end of the url. I just want to use the title for the current image but I'm unsure of where to retrieve it from.
You can see an example in any of the images here: http://www.sghalliday.com/urban2.html
I would also try and like to remove the hashtag from the end of the url when the user exits the gallery but that's not such a big deal for now.
Quick solution, alter these lines in prettyphoto.js and you are good to go. If title is empty URL will look ugly, but will be still functional ;)
...
...
if(!pp_alreadyInitialized && getHashtag()){
pp_alreadyInitialized = true;
// Grab the rel index to trigger the click on the correct element
hashIndex = getHashtag();
ergec = hashIndex.split("/"); // add this line
hashRel = hashIndex;
//hashIndex = hashIndex.substring(hashIndex.indexOf('/')+1,hashIndex.length-1); // comment this line
//hashRel = hashRel.substring(0,hashRel.indexOf('/')); // comment this line
hashIndex = ergec[ergec.length - 2]; // add this line
hashRel = ergec[0]; // add this line
// Little timeout to make sure all the prettyPhoto initialize scripts has been run.
...
...
function setHashtag(){
if(typeof theRel == 'undefined') return; // theRel is set on normal calls, it's impossible to deeplink using the API
location.hash = theRel + '/' + pp_titles[rel_index] + '/' + rel_index +'/'; // alter this line
};
...
...

show image in a new window

I am currently trying to open an image in a new window by clicking on it. But i cant seem to figure out where my code is wrong. Any solution?
function largePic(){
var imageNumber = document.getElementById("img2");
imageNumber = this.getAttribute('src').split(".", 1);
window.open(imageNumber[0] + "zlatan-stor.jpg");
}
You should try changing "this.getAttribute('src').split(".",1);" to
imageNumber.getAttribute('src').split(".",1);
Are you sure that #img2 is the one being clicked? If it isn't just do it like this:
function largePic(){
var imageNumber = document.getElementById("img2");
var link = imageNumber.getAttribute('src').split(".", 1);
window.open(link[0] + "zlatan-stor.jpg");
}
this will work only if the function is called inline (which you shouldn't do it, you should have your js code in a separated file)
This question is very similar to yours.
I think the main problem with your code is that window.open expects a URL and one isn't being provided.
Following the answer found at this link should allow you to separate the code into an external file, which as #Skatox mentioned, is a good practice.

How to add a second class in javascript using file url inside a directory?

I am using the following javascript to add the class based on url name.
$(function(){
var loc = window.location.pathname.match(/^\/?(\w+)\b/);
if(loc) $(document.body).addClass(loc[1].toLowerCase());
}
It is working fine except when the file is inside the directory it only adds the folder name and not the file name. I have added a second variable to add however I don't have the right expression it keeps adding the whole url products/nameoffile.php as the class
$(function(){
var loc = window.location.pathname.match(/^\/?(\w+)\b/);
var loc2 = window.location.pathname.match(/^\/?(.*)\b/);
if(loc) $(document.body).addClass(loc[1].toLowerCase());
if(loc2) $(document.body).addClass(loc2[1].toLowerCase());
}
I would like to know the right expression for adding the class to add for the second class for a file inside a directory. Instead of 'products/nameoffile.php' i want just 'nameoffile' for the class to be added to body.
Not using a regex but maybe this will point you in the right direction.
http://jsfiddle.net/aTnyk/
Don't use regex, just use a simple split() and pop():
var loc = window.location.pathname.split('/').pop();
try this:
$(function(){
var loc = window.location.pathname.split("/");
if (loc[loc.length-1]) {
var cls = loc[loc.length-1]].split('.');
$('body').addClass(cls[0].toLowerCase());
}
})
DEMO

onClick replace /segment/ of img src path with one of number of values

No idea what I'm doing or why it isn't working. Clearly not using the right method and probably won't use the right language to explain the problem..
Photogallery... Trying to have a single html page... it has links to images... buttons on the page 'aim to' modify the path to the images by finding the name currently in the path and replacing it with the name of the gallery corresponding to the button the user clicked on...
example:
GALLERY2go : function(e) {
if(GalleryID!="landscapes")
{
var find = ''+ findGalleryID()+'';
var repl = "landscapes";
var page = document.body.innerHTML;
while (page.indexOf(find) >= 0) {
var i = page.indexOf(find);
var j = find.length;
page = page.substr(0,i) + repl + page.substr(i+j);
document.body.innerHTML = page;
var GalleryID = "landscapes";
}
}
},
There's a function higher up the page to get var find to take the value of var GalleryID:
var GalleryID = "portfolio";
function findGalleryID() {
return GalleryID
}
Clearly the first varGalleryID is global (t'was there to set a default value should I have been able to find a way of referring to it onLoad) and the one inside the function is cleared at the end of the function (I've read that much). But I don't know what any of this means.
The code, given its frailties or otherwise ridiculousness, actually does change all of the image links (and absolutely everything else called "portfolio") in the html page - hence "portfolio" becomes "landscapes"... the path to the images changes and they all update... As a JavaScript beginner I was pretty chuffed to see it worked. But you can't click on another gallery button because it's stuck in a loop of some sort. In fact, after you click the button you can't click on anything else and all of the rest of the JavaScript functionality is buggered. Perhaps I've introduced some kind of loop it never exits. If you click on portfolio when you're in portfolio you crash the browser! Anyway I'm well aware that 'my cobbled together solution' is not how it would be done by someone with any experience in writing code. They'd probably use something else with a different name that takes another lifetime to learn. I don't think I can use getElement by and refer to the class/id name and parse the filename [using lots of words I don't at all understand] because of the implications on the other parts of the script. I've tried using a div wrapper and code to launch a child html doc and that come in without disposing of the existing content or talking to the stylesheet. I'm bloody lost and don't even know where to start looking next.
The point is... And here's a plea... If any of you do reply, I fear you will reply without the making the assumption that you're talking to someone who really hasn't got a clue what AJAX and JQuery and PHP are... I have searched forums; I don't understand them. Please bear that in mind.
I'll take a stab at updating your function a bit. I recognize that a critique of the code as it stands probably won't help you solve your problem.
var currentGallery = 'landscape';
function ChangeGallery(name) {
var imgs = document.getElementsByTagName("img") // get all the img tags on the page
for (var i = 0; i < imgs.length; i++) { // loop through them
if (imgs[i].src.indexOf(currentGallery) >= 0) { // if this img tag's src contains the current gallery
imgs[i].src = imgs[i].src.replace(currentGallery, name);
}
}
currentGallery = name;
}
As to why I've done what I've done - you're correct in that the scope of the variables - whether the whole page, or only the given function, knows about it, is mixed in your given code. However, another potential problem is that if you replace everything in the html that says 'landscape' with 'portfolio', it could potentially change non-images. This code only finds images, and then replaces the src only if it contains the given keyword.

Categories