I have a list of videos and a video player (div container). Need to show a video in the div container when a link is clicked. The video codes is given by a third party so I want to created a conditional statement to check what is clicked based on it's id, but is not working at all! I am pretty sure it is some syntax missing:
<script type="text/javascript">
function showVideo()
{
if(document.getElementById == videoA)
{
alert("videoA")
}
if(document.getElementById == videoB)
{
alert("videoB")
}
}
</script>
--------------------
Video A
Video B
You need to pass in the "this" value:
Video A
or:
Video A
Then in the handler:
function showVideo(anchor) { // assumes you used "this", like the 1st example
var videoId = anchor.id;
//
// ... show the video or whatever ...
//
}
You need to call the getElementById and pass in the id of the element as a parameter:
if(document.getElementById("videoA"))
The HTML you've included actually have the id misspelled
Video A
Video B
should be
Video A
Video B
The way you've structured your code will show an alert for both elements. If you want the id of the element clicked, you will have to get it from the Event object and do a comparison on that basis.
document.getElementById("videoB")
You want to actually call the getElementById function and pass in the ID as a paramater.
The current way returns:
document.getElementById
>>function getElementById() { [native code] }
So you are actually comparing that function pointer to a variable videoA(which doesn't actually seem to exist in your code).
However judging by your application, I'd actually attach an onclick handler to see which one was clicked.
Video A
and in your javascript:
function videoEvent(videoLink){
// videoLink is now the ahref element
}
If that's really the code you're using, it's not working because you have a typo in it: your HTML declares two IDs, one called vidoeA and the other called vidoeB, whereas your Javascript is testing for the correct spelling.
(You also need to put the ID name in quotes in your JS).
What you actually want is something like this:
HTML
Note: Your ID's were spelled incorrectly in your question.
Video A
Video B
JavaScript
function showVideo(elem) {
if(elem.id == "videoA") {
alert("videoA")
}
if(elem.id == "videoB") {
alert("videoB")
}
//or better yet, just:
//alert(elem.id);
return false; //Stops you from following the link.
}
Related
I'm fairly new to Javascript, and am trying to get an 'on click enlarge' kind of effect, where clicking on the enlarged image reduces it again. The enlarging happens by replacing the thumbnail by the original image. I also want to get a slideshow using images from my database later on.
In order to do that, I made a test where I replace the id which indicates enlarging is possible by a class and I also use a global variable so that I can keep a track of the url I'm using. Not sure this is the best practice but I haven't found a better solution.
The first part works fine, my image gets changed no problem, values are also updated according to the 'alert' statement. However, the second part, the one with the class never triggers.
What am I doing wrong (apart from the very likely numerous bad practices) ?
If instead of changing the class I change the id directly (replacing .image_enlarged by #image_enlarged, etc.), it seems to call the first function, the one with the id, yet outputs the updated id, which is rather confusing.
var old_url = "";
$(function(){
$('#imageid').on('click', function ()
{
if($(this).attr('class')!='image_enlarged'){
old_url = $(this).attr('src');
var new_url = removeURLPart($(this).attr('src'));
$(this).attr('src',new_url); //image does enlarge
$(this).attr('class',"image_enlarged");
$(this).attr('id',"");
alert($(this).attr('class')); //returns updated class
}
});
$('.image_enlarged').on('click', function (){
alert(1); //never triggered
$(this).attr('src',old_url);
$(this).attr('class',"");
$(this).attr('id',"imageid");
});
});
function removeURLPart(e){
var tmp = e;
var tmp1 = tmp.replace('thumbnails/thumbnails_small/','');
var tmp2 = tmp1.replace('thumbnails/thumbnails_medium/','');
var tmp3 = tmp2.replace('thumbnails/thumbnails_large/','');
return tmp3;
}
As for the html, it's really simple :
<figure>
<img src = "http://localhost/Project/test/thumbnails/thumbnails_small/image.jpg" id="imageid" />
<figcaption>Test + Price thing</figcaption>
</figure>
<script>
document.write('<script src="js/jquery-1.11.1.min.js"><\/script>');
</script>
<script type="text/javascript" src="http://localhost/Project/js/onclickenlarge.js"></script>
From the API: http://api.jquery.com/on/
The .on() method attaches event handlers to the currently selected
set of elements in the jQuery object.
When you do $('.image_enlarged').on(...) there is no element with that class. Therefore, the function is not registered in any element.
If you want to do so, then you have to register the event after changing the class.
Here's an example based on your code: http://jsfiddle.net/8401mLf4/
But this registers the event multiple times (every time you click) and it would be wrong. So I would do something like:
$('#imageid').on('click', function () {
if (!$(this).hasClass('image_enlarged')) {
/* enlarge */
} else {
/* restore */
}
}
JSfiddle: http://jsfiddle.net/8401mLf4/2/
Try using:
addClass('image-enlarged')
instead of:
.attr('class',"image_enlarged");
the best way to do this would be to have a small-image class and a large image class that would contain the desired css for both and then use addClass() and removeClass depending on which you wanted to show.
I realize that this posting is possibly a repeat of this one:
Using Javascript to dynamically create links that trigger popup windows
But I'm not good enough at JavaScript to understand how to apply it to the context in which I'm trying to do it.
I'm creating a javascript snippet that could possibly be called multiple times from within a CMS (Umbraco ) that generates webpages.
An id (variable name: mediaid) is passed into this context and I want to dynamically create a link that has an onclick event to launch a popup. I take the ID passed into the context I'm working in (Umbraco calls them "macros") and append the id as a query string to a different URL (same domain) so that the resultant page can do some stuff with the id.
What I have works, but only for one instance on a page. I need a user to be able to insert multiple dynamic links on a page. Right now, the last link generated uses the onclick event for all instances on the page.
<script>
var linkWithQueryParam = 'http://www.mydomain.org/test2?yourkey=<xsl:value-of select="$mediaid" />';
var element = document.createElement("a");
element.id = '<xsl:value-of select="$mediaid" />';
element.href = '#';
element.onclick = function() {
setLink(linkWithQueryParam);
}
function setLink(value) {
window.open(value, 'player', 'width=775,height=520,location=0,directories=0,status=0,menubar=0');
}
document.body.appendChild(element);
element.appendChild(document.createTextNode('Listen To This Audio'));
</script>
So, for example, I have a template elsewhere, that calls this macro I created, twice:
<umbraco:Macro mediaid="4107" Alias="audioPlayerPopUp" runat="server"></umbraco:Macro>
<umbraco:Macro mediaid="26502" Alias="audioPlayerPopUp" runat="server"></umbraco:Macro>
The links are generated, but when I click on them, the link generated above in "linkWithQueryParam" is always whatever the last one was, for all links.
I thought maybe if I set the "id" attribute of the link to make it unique, it would work. But that doesn't work. How can I make the dynamically generated onclick event unique?
I ended up changing my approach and using an event delegate per unclenorton's response in this s.o. post
http://davidwalsh.name/event-delegate
I used a variation on the example to only disable the default link behavior, first checking to see that the link class is matched. This script relies on a named div that is available sitewide and is placed at the bottom of a master template so it is available:
<script>
document.getElementById("main").addEventListener("click", function(e) {
if(e.target)
{
if(e.target.nodeName == "A")
{
if(e.target.className == "miniplayer")
{
if(e.preventDefault) {
e.preventDefault();
}
else
{
e.returnValue = false;
}
var target = e.target;
var popupWindows = window.open(target.href, 'player', 'width=775,height=520,location=0,directories=0,status=0,menubar=0');
}
}
}
});
</script>
I then edited my user macro to simply place the class "miniplayer" on each link it creates and include the media id as a query parameter to another url which provides the media player. That other url resource then pulls the query param id out of the url and looks up the link to the media item. But the .js above launches the pop-up the way that I want.
One challenge I had was on how to dynamically assign the resultant media resource to the player (in this case, jPlayer). I found that if I write the media url to a hidden div, I can then just tell the jPlayer to read the value from it.
So I have a second macro which gets the query param and writes it to a hidden div:
<div style="display:none" id="audioUrl"><xsl:copy-of select="$mediaNode/audioUrl" /></div>
Finally, I adjust the jPlayer jQuery to read the url from the hidden div:
$(this).jPlayer('setMedia', {mp3: $("#audioUrl").text() }).jPlayer("play");
It doesn't seem like the best solution. I don't like passing the mediaid through the url, but it fulfills all my other requirements
The issue here is with globals and closures. The linkWithQueryParam variable is a global that is updated each time that script is added. When you click on the link it goes and fetches the url from the variable which is of course the last one.
You can fix this a few ways,
Wrap this code in an immediate anonymous function. This will reduce the scope of the variables to within the anonymous function.
Set the URL when the script is run instead of when the link is clicked.
I'm having a bit of trouble getting my head around this thing so I thought it might help to post it here. So here it goes.
What I have: 5 different images in 5 different table cells + a script that I will post below.
What I want: to use the javascript's...
document.GetElementById("image ID").style.visibility='visible/hidden'
...after a preset time, but, instead of image ID there is a string that gets the ID of the image, and before anyone says anything, I am not using "" for the string that is inside of (). Something like...
var n=1;
function picID() {
pictureID="pic"+n;
n=n+1;
}
...and this way, every time that function is called we get the element ID of "pic1", "pic2", "pic3", etc.
What my problem is: the darn thing won't work. The image styling remains the same as I defined it in the img tag. (style="visibility:hidden")
All image ID's are within the img tag, as it should.
Here's the whole code:
<script>
var m=1;
function Show() {
if (m==6) {m=1;}
feat="feat"+m;
**document.getElementById(feat).style.visibility="visible";**
m=m+1;
setTimeout('Show()', 3000);
}
window.onload = Show;
</script>
<script>
var k=1;
function Hide() {
if (k==6) {k=1;}
feate="feat"+k;
**document.getElementById(feate).style.visibility="hidden";**
k=k+1;
setTimeout('Hide()', 3000);
}
window.onload = Hide;
</script>
I've separated the code so it'd easier to spot.
From what I've seen the only issue is the bold line within the code. I've tested everything else by replacing the document.getElementById with document.write, so I can see that the custom ID string thingy is working fine. It is. An everything else as well.
Any suggestions? Thanks.
Try setting k = 0; instead of k = 1;
It looks like when you load the page you have both the show() and the hide() functions running on the same element. Doing the above will make hide() run on the element BEFORE the element the show() runs on.
This code will keep on running in a loop.
because the setTimeOut() is called every time.
There should be a case when its not called
e.g if m<6 call it else don't
Using Jquery, I've managed to make a dropdown login form triggered by clicking a button. However, I am also trying to change the direction of the arrow next to it by replacing the src image, and it appears to do nothing.
$("#login_panel").slideToggle(200).toggle(
function() { $("#arrow").attr('src', '/src/east.gif';) },
function() { $("#arrow").attr('src', '/src/south.gif';) }
);
This can be seen at:
http://dev.mcmodcenter.net (The 'Login' button)
$(document).ready(function() {
$("#login_panel").slideToggle(200).toggle(
function() { $("#arrow").attr('src', '/src/east.gif';) },
function() { $("#arrow").attr('src', '/src/south.gif';) }
);
for (var i = 0; i < 2; i++) {
$(".mod").clone().insertAfter(".mod");
}
$(".mod").lazyload({
effect: "fadeIn"
});
});
You can directly access this.src - no need to create a new jQuery object for that:
$('#arrow').toggle(
function() { this.src = '/src/south.gif'; },
function() { this.src = '/src/east.gif'; }
);
And if you prefer to do it via .attr() at least use $(this) (DRY - don't repeat yourself - in this case, don't specify the selector more often than necessary)
$("#arrow").toggle(
function(){$("#arrow").attr("src", "/src/south.gif");},
function(){$("#arrow").attr("src", "/src/east.gif");}
);
You left off the "#" in the handler functions. By just referring to "arrow", you were telling jQuery to look for (presumably absent) <arrow> tags.
Now, as to the larger situation, what you're setting up there is something that'll make the image change when the image itself is clicked. Your description of your goal makes me think that that's not quite what you want, but it's hard to tell. If you want some other element to control the changes to the image, then you'd attach the handler(s) elsewhere.
Is the image you want to change that little black arrow next to the login button? If so, then what should happen is that the code to set the image should be added to the existing handler that slides the login form up and down. (By the way, in Chrome the login box shows up in what seems like an odd place, far to the left of the button.)
looks like you forget to put the # before the arrow in $("arrow")
it should be like this
$("#arrow").toggle(
function(){$("#arrow").attr("src", "/src/south.gif");},
function(){$("#arrow").attr("src", "/src/east.gif");}
);
$("arrow") will match <arrow>, you lost the #
Also, the toggle method does not take two functions as its arguments, it works in a completely different way to what you are trying to do with it. Yes, it does, there are two different toggle methods for jQuery (insert rant about awful API design)
And now you have completely edited the code…
Your code now immediately assigns strings to the this.src (where this is (I think) the document object), and then passes those two strings as arguments to the toggle method (which are not acceptable arguments for it)
And now you have completely edited it again…
This code should work:
$('#login_button').click(function() {
$(this).find('#arrow').attr('src', function(i, v) {
return v.indexOf('east.gif') < 0 ? '/src/east.gif' : '/src/south.gif';
});
$('#login_panel').slideToggle(200);
});
I am trying to give a button an onclick event when a certain thing on a page changes. I have tried to do it many different ways and none have worked. What am I doing wrong?
Below are what I have tried.
document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); };
document.getElementById(subDiv).onclick = "alert('Error. There is an error on the the page. Please correct that then submit the page');";
function redErrorAlert()
{
alert('Error. There is an error on the the page. Please correct that then submit the page');
}
document.getElementById(subDiv).onclick = redErrorAlert;
document.getElementById(subDiv).setAttribute('onclick',redErrorAlert(), false);
document.getElementById(subDiv).setAttribute('onclick','redErrorAlert()', false);
Note: subDiv is a variable containing the id of the element.
You need to wait for the DOM tree to be created before you do queries on it.
Make sure that this all happens within a context that is created after the DOM tree has been built:
window.onload = function() {
document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); };
};
document.getElementById() takes a string containing the ID of the element you're trying to find. Assuming you're looking for the element with id 'subDiv', you should be calling document.getElementById('subDiv').
(It's also possible that the variable subDiv in your code is a string containing the ID, but since you didn't mention it I'm assuming that it doesn't.)
EDIT: If you were to go with virstulte's suggestion of using jQuery, you'd attach a function to the document.ready event in order to ensure that the DOM has been built by the time your code runs. Example:
$(document).ready(function() {
$("#subDiv").click(function() { alert("Test!"); });
});
This sounds like jQuery territory here. Once you learn the ins and outs of jQuery, things like this are a snap to take care of, and you'll find yourself writing a lot less JavaScript.
First, get jQuery from http://jquery.com/
Then put this in your code to bind the event:
$('#idOfElementToBindClickEvent').click(function(){
alert('Error.');
});
jQuery basically provides a way to manipulate elements using CSS-like selectors.
try
document.getElementById(subDiv).onclick = alert('Error. There is an error on the the page. Please correct that then submit the page');
or
function redAlert() {
alert('Error. There is an error on the the page. Please correct that then submit the page');
}
document.getElementById(subDiv).onclick = redAlert();
First case: you need to call the function, and you've assigned a string
Second case: you've assigned a function and you were not calling this function