Multiple Instances of a JavaScript Rollover - Stopped Functioning - javascript

So, I've been using this JavaScript Snippet through out a fairly large website for rollovers:
<img src="img/vendorbuttons/bn_off.gif" name=bn_off border=0>
Which has worked great, and effortlessly, until now - I have a couple pages that will use the same rollover images for Buy Buttons across the pages, they will be the same aside from a different link being implemented. -Once I began using that JS, with using the same images more then once, all of the JS rollovers stopped work and don't render the 'off state'.
Ultimately - apparently, I can't have multiple JS rollovers using the same images more then once with this code? Any suggestions?

Are you sure nothing was changed? Images or code?
Since there isn't any clue here in the html (because you say it worked earlier), I can only suggest the following:
href="http://www.barnesandnoble.com" , name="bn_off" and border="0" <- these attribute values are missing double-quotes in your code.
Also try adding id="bn_off" (You already have name="bn_off", keep that too).
EDIT:
I think I know why. Because you are copying and pasting this to use in multiple locations, you get multiple links with the SAME name bn_off, and that is why it stops working.
It could have been WAY more easier with jQuery and/or CSS but here's what you can do with what you have:
Add these two functions inside a script block in the HEAD section of your html:
function OnMouseOver(link)
{
if (document.images)
{
var imageElements = link.getElementsByTagName("img");
imageElements[0].src = 'img/vendorbuttons/bn_on.gif';
}
}
function OnMouseOut(link)
{
if (document.images)
{
var imageElements = link.getElementsByTagName("img");
imageElements[0].src = 'img/vendorbuttons/bn_off.gif';
}
}
Change your html for the links like this:
<a href="http://www.barnesandnoble.com" onMouseOver= "OnMouseOver(this);" onMouseOut= "OnMouseOut(this);">
<img src="img/vendorbuttons/bn_off.gif" name="bn_off" border="0">
</a>
Now you can copy and paste the links as much as you want, the javascript won't depend on the name.
If I was you, I would use jQuery and CSS to simplify things.
Hope this helps.

this is how to fix your existing script. However, Guganeshan's solution is much cleaner.
<img src="img/vendorbuttons/bn_off.gif" border=0>

Related

Toggling an html IMG element's class using JS (no Jquery)

I give up... All of your answers were just different ways of targeting the local element.
If you bothered to actually read what I was saying you would realise that it was not a problem with the code I already had, just that the code DID NOT work on IMG tags.
While faffing around trying to demonstrate my problem (and that none of your solutions did anything different to what was already happening) I found that I can achieve exactly what I want by applying a Grayscale filter to a DIV element placed over each image. The mouseover event then triggers an opacity change in the DIV element.
It is a little heavier that I wanted but it answered my ACTUAL question. The answer being:
Yes, there probably is a way to toggle class of IMG tags. But no, I am probably not going to find it here without causing arguments or being told i'm using "bad code". So yes, it IS easier and more efficient to target DIV elements.
By the way, page load times are about how large data packages are. Larger data packages (images, html/css/js documents, etc) take longer to download and so the page takes longer to load. The website I am trying to create proves this thesis, I have an almost complete and (almost) fully functional website with loads of 'clever' little effects all under 20mb, about 15mb of which is images. This website is clean and simple, is hosted on my Samsung Galaxy Tab 4 (using Papaya) and loads almost instantly.
THIS is what I meant by "I want this to be VERY lite". Thank you all for your attempts to help, it's just a shame that I couldn't get anyone to understand what was going on.
If you add onClick to image element you don't need to pass anything, you will receive MouseEvent which contains all information. You need target from event.
I suggest to not use onClick on element as it is not scalable, you have to add it to all elements. Better to add listener to wrapping/container element and then filter target by some attribute e.g data-something Please check fiddle
So you have wrapping element and you images:
<div class="images-container">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" data-toggleable class="thumb-gray thumb-color" />
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" data-toggleable class="thumb-gray" />
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" data-toggleable class="thumb-gray" />
</div>
and you attach listener to you wrapping element. It is best practice as you don't attach listeners to each element and same time you are able easily scale your solution
var imagesContainerEl = document.querySelector('.images-container');
imagesContainerEl.addEventListener('click', function(event) {
var element = event.target;
if (element.hasAttribute('data-toggleable')) {
element.classList.toggle('thumb-color');
}
});
The same code can be extended to support mouseover and mouseout. Check fiddle2. One function to rule them all and in the darkness bind them..
var imagesContainerEl = document.querySelector('.images-container');
imagesContainerEl.addEventListener('mouseover', onToggleImage);
imagesContainerEl.addEventListener('mouseout', onToggleImage);
function onToggleImage(event) {
var element = event.target;
if (element.hasAttribute('data-toggleable')) {
element.classList.toggle('thumb-color');
}
}
Also updated fiddle which shows how to make image grayscale/color
Is what you refer to in your question as
onClick="colorFunction(image1)"
an inline javascript event listener?
If so, try replacing it with:
onClick="colorFunction(this)"
and rewrite colorFunction() as:
function colorFunction(image) {
image.classList.toggle('thumb-color');
}

How to document.write() within an image src string? Doesn't get parsed

This is for a Javascript application that is only intended to run on a local machine, accessing many large image files from local disk.
Original code like this:
<script>
// Constants, var inits, etc.
</script>
<-- Then html stuff including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()" src="buttons/but_run.png">
<--then a chunk of javascript related to the buttons -->
The thing works OK, see http://everist.org/NobLog/20150424_js_animated_gallery.htm
Now I want to extend it, so all image pathnames are defined as js constants and vars.
Some will remain fixed during lifetime of the browser page, others will change by
user actions.
I'm stuck with one part of this.
How to get the html parser to pay attention to script blocks WITHIN <img .... > statements?
Specifically, I want to do a document.write() within the image src string.
Like: <img src="<script>document.write(B_PATH)</script>something.png">
This is for the initial page display. The images later get changed by scripts, and that's working OK.
But the html parser doesn't seem to notice scripts inside html elements.
I'm a javascript nubie, so I may have some stupid misconception of how it all works.
Am I just doing it wrong, or is this fundamentally impossible due to reasons?
Here's an example:
<script>
// Constants
PGL_BUT_PATH = "buttons/" // where the button images etc are.
</script>
<-- some html stuff -->
<-- including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png">
<--then a chunk of javascript related to the buttons -->
In debugger, the img element appears as:
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png"/>
The intent was to get this:
<img id="pgb_runStop" onclick="click_runStop()"
src="buttons/but_run.png"/>
I could just give up with trying to have the page initially render with the correct buttons, and have js correct them afterwards. I'm just surprised... Isn't it possible to evaluate js constants during initial html parsing to construct the DOM, in this way?
Edit to add:
Sorry, I wasn't clear enough in the question. What I want is a way for js to make the html content/DOM correct (per js config values that get defined very early on) BEFORE the page first renders. To avoid any flicker or resizings after first render.
So another solution would be to delay the first page render till after some scripts have run, so they can make initial DOM adjustments before the user sees anything. Any way to do that?
Hmmm... actually that would solve another problem I have. I'll try searching for that.
The semantic templating tools suggest are interesting (had never heard of it. http://www.martin-brennan.com/semantic-templates-with-mustache-js-and-handlebars-js/ ) but am I correct that all such scripting add-ons will execute after the page first renders?
You cannot embed a tag within another tag's attribute. So you cannot embed a <script> inside the src of an <img>. That's just invalid won't-be-parsed HTML.
What you can do, though, is write the attribute after the fact:
<img id="uniqueId">
<script>
var img = document.getElementById('uniqueId')
img.setAttribute('src', PGL_BUT_PATH)
</script>
The <img> tag without a src attribute in that is invalid HTML technically, although it will probably work in any browser anyway. But if you want to stay totally legit, create the <img> with JavaScript too.
<div id="uniqueId"></div>
<script>
var elem = document.getElementById('uniqueId');
var img = document.createElement('img');
img.setAttribute('src', PGL_BUT_PATH);
elem.appendChild(img);
</script>
Tthough I really have no idea why would you like to do this.
This one works for me
<img id="pgb_runStop" onclick="click_runStop()"
src = "about:blank"
onerror="javascript:this.src = PGL_BUT_PATH + 'but_run.png'; this.onerror = null;>
or Another way
<script>
function createImg(src) {
document.write("<img src='" + src + "'>");
}
</script>
<script>createImg(PGL_BUT_PATH + 'but_run.png')</script>
Another more generic approach
<script>
function templete(temp, src) {
document.write(temp.replace("$STR", src));
}
</script>
<script>templete('<img id="pgb_runStop" onclick="click_runStop()" src="$STR"/>', PGL_BUT_PATH + 'but_run.png')</script>
Javascript isn't a templating engine in and of itself, and it looks like that's what you're trying to achieve here. Look into a javascript template library such as Handlebars and you'll have more luck.
Unfortunately, JavaScript doesn't work that way you are setting the src to <script></script> which all the browser thinks of it is just a weird URL. Try:
document.getElementById('pgb_runStop').src = PGL_BUT_PATH + 'but_run.png';
You can change pgb_runStop to whatever is the id of the element.
You can use a Framework like Angular.js to do things like that. I don't use angular.js myself but you can of some pretty incredible stuff with it.
Here's a list of even more engines that you can use
You can also use:
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
Basically, you can do:
(function(){window.onload=function(){
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
};}());
Which should function the exact same
Why not write the whole image in:
document.write('<img src="' + PGL_BUT_PATH + 'but_run.png"/>');
Fiddle

jQuery .attr Not Working Properly, Miss-Retrieving Links

This is a page I'm currently working on as a project
$(function() {
$(".modal-launcher, #modal-background").click(function() {
$(".modal-content, #modal-background").toggleClass("active");
$(".vid-1i").attr("src", "link1");
$(".vid-2i").attr("src", "link2");
$(".vid-3i").attr("src", "link3");
$(".vid-4i").attr("src", "link4");
$(".vid-5i").attr("src", "link5");
$(".vid-6i").attr("src", "link6");
$(".vid-7i").attr("src", "link7");
$(".vid-8i").attr("src", "link8");
//$('html').toggleClass('active').css('top', -(document.documentElement.scrollTop) + 'px');//
});
});
above the actual links are replaced just to display a quick idea of the bad jQuery.
In it, I am attempting to create my own popup launcher for videos; however, I am having trouble using jQuery to replace the "" src of an iframe element to a YouTube link. I am unable to figure out why the jQuery is not working. I understand that the jQuery is, of course, working properly, and that it is me who has written the code incorrectly, but here I am asking if anyone is able to figure out what it is I've done wrong, or what can be changed to make it work.
For some reason, the last video in the jQuery list is always the one retrieved.
Understand that the images are missing from the page due to them being local files and not network locations. Clicking above the captions that read like "Match One" will have the "intended" result, regardless if the image is showing or not.
Coming back to this and understanding more of JavaScript and jQuery, my problem was simply misunderstanding the code. In order to do something like this, one function per link would be more suitable.
function video1()
{
$("#popup, #modal-background").toggleClass("active");
$("#popup").prop("src", "https://www.youtube.com/embed/7h1s15n74r3all1nk");
document.getElementById('scroll').style.cssText ='overflow:hidden';
}
complementary html would look like this:
<div onclick="video1()"></div>
The previous code would run each line, effectively setting the last link as the source of the element. The new code is button independent, ensuring only one link belongs to each button.

css display:none for responsive web design

Need advice on what's the best solution to this.
I'm doing a RWD Photo Gallery page. Basically, i'm using pretty photo if accessed through a desktop and photoswipe when accessed in mobile devices.
What i did is this:
<img src="sample_image" />
<img src="sample_image" />
I hide (display:none) one of them depending of the screen size using media queries.
Is this a right approach, i read that using display:none will not reduce the load time. I have hundreds of photos in my gallery and i'm worried this might greatly affect the load time. Is there any good solution to this?
Why do you need two tags for this?
<img src="sample_image" />
<img src="sample_image" />
You can achieve the same with a single tag.
<img src="sample_image" />
Now with media query you can have the same desktop_and_mobile class on both media query and define the css property accordingly in each.
This has the advantage that you will be loading only one image, instead of two.
I think that what you want is to have the anchor tag to call the correct lightbox when clicked, because styling the sample_img with responsive css will work as expected, no need for fancy stuff, but if i'm correct then you have 3 choices in my opinion, you can do it like you said and hide the .desktop links using media queries, since the images are exactly the same the user wont have to load again that image, and being set to display:none the user browser won't render that element, so the only downside is that you will have a cluttered html and it will feel muddy, but no other concern in my opinion.
Another option is to use a js code like this one, but since usually lightbox codes will have a method to add event handlers to every link they find with (with the proper formating, lets say its rel), you will have to manually trigger that event after you changed the links rel attr, or execute adaptLinks() before that happens, in that case, on windows resize it won't work, unless you do what i said before. For that you can check how to do it on the lightbox page, they propably have that method listed.
Here is the code
var adaptLinks = (function(){
var $winHeight = $(window).height();
var $lightBoxLinks = $('a.lightBox');
return function() {
var isPrettyPhoto = false;
if($winHeight < 1000){
$lightBoxLinks
.removeClass('desktop')
.addClass('mobile')
.attr('rel','external');
} else {
$lightBoxLinks
.removeClass('mobile')
.addClass('desktop')
.attr('rel','prettyPhoto');
isPrettyPhoto = true;
}
// Call the link processing method of the lightbox
if(isPrettyPhoto) {
$lightBoxLinks.prettyPhoto();
} else {
// photoSwipe method
}
}
})();
$(window).resize(adaptLinks());
And the thir option, is use a lightbox that works both for desktop and mobiles, i think that is the right way to do it.
Good luck.

images being replaced when I want the next image just added

I have a javascript function which animates images like a slide show. What I'd like is to just have the images being displayed one after another from left to right.
I can't seem to find where in the code the images is getting replaced.
var realoffset = d.offset % d.total;
$(this)
.html(d.titles[realoffset])
.attr('action','article:'+(realoffset+1))
.fadeIn(600);
$(this)
.siblings('img')
.attr('src',function(i,attr){
return attr.replace(
/.+(\/large\/[a-zA-Z\.-_]+)$/,
d.locations[realoffset]+'$1'
)
})
.attr('action','article:'+(realoffset+1))
.fadeIn(600);
.attr('src',function(i,attr){
return attr.replace(
/.+(\/large\/[a-zA-Z\.-_]+)$/,
d.locations[realoffset]+'$1'
)
})
This code is replacing the src of the img tag. You're going to want to be inserting new img tags to show them side by side, not replacing the current tag's src.
Did you write that jQuery snippet yourself? I'm guessing not. Anyway, there are a lot of factors involved in creating a "slideshow" with JavaScript. It sounds like you just need some general knowledge about the subject.
First, let's get your vision straight. Based on your code, you seem to want to fade images into view as they are cycled in the slideshow. For that, study this example:
http://jsfiddle.net/Y6fnx/1/
Now, your code does stuff with d.titles; purely by inference I'm guessing that this displays the image and also a caption for the image? For that, study my updated fiddle:
http://jsfiddle.net/ESP9S/1/
There are countless ways to create a slideshow! You can implement auto-play by taking advantage of JavaScript's setTimeout. You can load your captions from somewhere else. You can get your images from a external script (like Barbara mentioned). You can slide your images instead of fading them by playing with jQuery animate. It never ends!

Categories

Resources