managing mousever and mouseclick events - javascript

I am trying to do something quite simple.
I have an image with a rollover. When it is clicked the onmouseout and onmouseover events are removed and the image is swaped. Up to here I got it but now I would like to add something so that when it is clicked again everything returns to the original state (swap the image again and activate onmouseover and onmouseout.
Here is the code I got so far:
<a href="#"
onMouseOut="MM_swapImgRestore();
"
onMouseOver="MM_swapImage('image','','images/image-2.jpg',1)"
onClick="
MM_swapImage('image','','images/image-3.jpg',1);
this.onmouseover=null;
this.onmouseout=null;
"
>
<img name="image" src="images/image-1.jpg" id="rond9"></a>

for my quite easy solution i would add a flag and check it before firing the mouseover and mouseout events as it it remove the unnecessary burden of attaching and detaching of events.
i.e like:
<script>var myFlag=true;</script>
<a href="#"
onMouseOut="if(myFlag === true){MM_swapImgRestore();}"
onMouseOver="if(myFlag === true){MM_swapImage('image','','images/image-2.jpg',1);}"
onClick="MM_swapImage('image','','images/image-3.jpg',1);
myFlag = !myFlag;"
>
<img name="image" src="images/image-1.jpg" id="rond9"></a>

Seeing as this was generated by a WYSIWYG editor (presumably DreamWeaver), I won't suggest a jQuery implementation, but rather something that would work without referencing jQuery. You could possibly try something like:
<script type="text/javascript">
var removeEvents = true;
function EventAttach(anchor) {
MM_swapImage('image','','images/image-3.jpg',1);
anchor.onmouseover = removeEvents ? null : new function() { MM_swapImage('image','','images/image-2.jpg',1) };
anchor.onmouseout = removeEvents ? null : new function() { MM_swapImgRestore(); };
removeEvents = !removeEvents;
}
</script>
<a href="#"
onMouseOut="MM_swapImgRestore();"
onMouseOver="MM_swapImage('image','','images/image-2.jpg',1)"
onClick="EventAttach(this);"
>
<img name="image" src="images/image-1.jpg" id="rond9"></a>

Related

Creating a javascript variable that adds 1 when an event happens

Context: I'm helping my friend create a political joke sort of website.
I need it to add 1 to a variable every time the onmouseover event is triggered.
<img src="tm.png" onmouseover='this.src="jc.png"'>
I have this so far but I need to find a way to link it with a function that will add 1 to itself when that event happens. I have multiple onmouseover events around the page so I need it to work for them all. I know how to make the variable but I am unsure on how to add 1 each time the onmouseover event happens, I am also unsure on how to add the function to the onmouseover event. Thanks
hoverCounter = 0;
<img src="http://www.darbsterkitty.com/uploads/5/5/5/6/55568079/b8sk1f_orig.jpg" height="200px" onmouseover="hoverCounter++; console.log('hoverCounter: ' + hoverCounter)"></img>
Use event delegation and check whether the hovered element is an image.
var count = 0;
addEventListener("mouseover", function(e){
if(e.target.tagName == "IMG"){
count++;
}
console.log(count);
})
<img src="http://lorempixel.com/50/50?0"/>
<img src="http://lorempixel.com/50/50?1"/>
<img id="someImage1" src="http://via.placeholder.com/350x150" >
<img id="someImage2" src="http://via.placeholder.com/350x150" >
<br/>
Hover Count:
<input id="countDisplay" type="text"/>
JS:
// Initial count
var hoverCount = 0;
// Function to increment
function onHovered(event){
hoverCount++;
document.getElementById('countDisplay').value = hoverCount;
}
// Bind events
document.getElementById('someImage1').onmouseover = onHovered;
document.getElementById('someImage2').onmouseover = onHovered;

Append a div outside of the input parent

Im fairly new to javascript and I just can't figure this out despite my attempt in researching. How do I track the change of a input within a div and trigger an append to an outside div? My code goes as follow:
Append h3 with "Pending" once ".image-value" input has a change in value
<!-- APPEND <h3> -->
<h3>Best Overall Costume<div class="pending">Pending</div></h3>
<div>
<div class="select-form">
<img src="images/vote.jpg" data-value="image_value">
<img src="images/vote.jpg" data-value="image_value2">
<img src="images/vote.jpg" data-value="image_value3">
<img src="images/vote.jpg" data-value="image_value4">
<img src="images/vote.jpg" data-value="image_value5">
<!-- Track the change of this input -->
<input type="hidden" class="image-value" name="selected_image" value="">
</div>
</div>
I tried this:
function changeStatus(statusValue) {
$("input",".select-form").val(statusValue).trigger("change");
}
$("input",".select-form").change(function(){
if (!$(this).val()){
$("<div class='pending'>Pending</div>").appendTo($("h3").prev($(this)));
}
});
But that didn't seem to work. Any ideas?
place an empty div where you want your new div and give it an id i.e(<div id='myDiv'><div>) and then append what you want like this.
$( "#myDiv" ).append( "<div class='pending'>Pending</div>" );
You can also check Append Explained
for more explanations.
Thanks.
I've done a couple things here... First, I'm not sure why you had it all in a named function. When you're using event listeners that often isn't necessary.
Then, I don't know what the val check was for, so I reversed it.
Finally, I'm using one(), which only runs once. This case seemed to call for that.
$('.select-form').one('change', 'input', function () {
if ( $(this).val() ) { alert('asdgf');
$("<div class='pending'>Pending</div>")
.appendTo($(this).parent().prev('h3'));
}
});
Fiddle
try this:
$("input",".select-form").on("change", function(){
var $this = $(this);
if (!$this.val()){
var elem = $('<h3>Best Overall Costume<div class="pending">Pending</div></h3>');
$this.parent().parent().before(elem);
}
});
you can also place a check, that if the pending div is already added, not to add it again.
Of course this solution assumes that there are no other nested divs between the target div(before which you want to append) and the input control

multiple classes and id's in jquery not working in safari

The below code is working in firefox and chrome but not in safari. Can anybody tell me if this is the correct way to add multiple classes and id's in jquery?
jquery
$(document).ready(function () {
$('.imgLink, .imgLink1, .imgLink2, .imgLink3, .imgLink4, .imgLink5, .imgLink6,
.imgLink7, .imgLink8, .imgLink9').click(function () {
var imgPath = $(this).attr('href');
$('#theImage, #theImage1, #theImage2, #theImage3, #theImage4, #theImage5, #theImage6,
#theImage7, #theImage8, #theImage9').attr('src', imgPath);
return false;
});
});
html for .imgLink
<a class="imgLink1" href="http://www.customtie.com/images/press/printwear-11-2013.jpg">Printwear Nov 2013</a>
hmtl for #theImage
<img id="theImage" src="http://www.customtie.com/images/press/counselor-2-2014.jpg" alt="" width="auto" height="auto">
Ugh... Classes are not meant to be used that way. Rather:
FOO
BAR
<img id="theImage1" src="images/default.jpg" alt="">
<img id="theImage2" src="images/default.jpg" alt="">
$(function () { // DOM ready shorthand
$('.imgLink').click(function ( e ) {
e.preventDefault();
var imgPath = $(this).attr('href');
var targetID = $(this).data('targetid');
$('#theImage'+ targetID).attr('src', imgPath);
});
});
|→ jsBin demo
So basically you add the same class to all your clickables, and a data-* attribute with the number of the image ID suffix you want to target.
There's also other nice ways (even simpler) to achieve the same, but without seeing some HTML it's blind guessing.
I would first agree with m90's suggestion that you want to just add a single class to all these elements and select off that.
But I would presume that the issue is the carriage return halfway through your string. If you want to start a new line, you have to end the first one and then concatenate them together like this:
$('.imgLink, .imgLink1, .imgLink2, .imgLink3, .imgLink4, .imgLink5, .imgLink6,'+
'.imgLink7, .imgLink8, .imgLink9').click(function () {
var imgPath = $(this).attr('href');
$('#theImage, #theImage1, #theImage2, #theImage3, #theImage4, #theImage5, #theImage6, ' +
'#theImage7, #theImage8, #theImage9').attr('src', imgPath);
return false;
});

Replace every onclick of the page with img src link?

I use a webpage where I want to replace the onclicks, of a bunch of links, with the modified src link of the <img> each link contains.
For example, the Greasemonkey script should change this:
<p class="listphotos">
<a onclick="alert('I'm a really annoying function! X'); return false;" href="#">
<img alt="photo" src="http://.../min/x.jpg">
</a>
<a onclick="alert('I'm a really annoying function! Y'); return false;" href="#">
<img alt="photo" src="http://.../min/y.jpg">
</a>
</p>
To this:
<p class="listphotos">
<a onclick="http://.../max/x.jpg" href="http://.../max/x.jpg">
<img alt="photo" src="http://.../min/x.jpg">
</a>
<a onclick="http://.../max/y.jpg" href="http://.../max/y.jpg">
<img alt="photo" src="http://.../min/y.jpg">
</a>
</p>
I've tried this (see also this jsFiddle):
var link = $("p.listphotos a img").prop("src").replace("min", "max");
$("p.listphotos a").prop("onclick", link);
$("p.listphotos a").prop("href", link);
but the right pictures do not get linked.
Setting onclick to a link is an error. onclick needs to be valid javascript. But, since it looks like you're trying to "delink" those photos, best to remove the onclicks altogether.
Also, you can't set the href that way (unless you want every link to go to the same photo). You need to loop. jQuery's .each() should do the trick. Like so:
$("p.listphotos a img").each ( function () {
//-- `this` is each target image, one at a time
var jThis = $(this);
//-- More robust replace
var bigLink = jThis.prop ("src").replace (/\bmin\b/i, "max");
//-- The img parent is the link we're after.
jThis.parent ().prop ("href", bigLink).removeProp ("onclick");
} );
Note that prop and removeProp are the correct way to kill an onclick. But, if you inspect the page source in some browsers, the attribute will still be there. Don't worry, the onclick will no longer function.
I think you can try something like this
var numberClick=0;
var Images= ['image1.png','image2.png'];
function changeIndex(index){
if (index >=0 && index < Images.length){
$("p.listphotos a img").attr("src", Images[index]);
return true;
}
return false;
}
then you can use it in this way
function showImage(){
if (changeIndex(numberClick)){
numberClick+=1;
}
else{
numberClick=0;
}
}
and then
$("p.listphotos a img").click(function(){
showImage();
return false;
});

Javascript hide/show - more elegant way to do this?

I'm looking for a more elegant way to make a hide/show of divs using inline Javascript.
If you mouse over the orangish/yellow circle logos over the cars the tag should appear. When moused out they should disappear.
URL:
http://174.120.239.48/~peakperf/
<div class="second">
<div id="speech2" style="display: none">
<img src="<?php bloginfo('template_url'); ?>/images/speech2.png" width="334" height="50">
</div>
<a id="various2" href="#inline2,javascript:HideContent('speech1')" title="" onmouseover="HideContent('speech1'); return true;">
<img src="<?php bloginfo('template_url'); ?>/images/clicker.png" width="62" height="50" onmouseover="document.getElementById('speech2').style.display = 'block'" onmouseout="document.getElementById('speech2').style.display = 'none'">
</a>
</div>
Here's the pastebin of the code used:
http://pastebin.com/JsW6eJRZ
The more elegant solution is to utilize JQuery.
Once you include the library into a file, a div show is done using the following selector
$('#idOfDiv').show();
Or if there are no ids but rather classes
$('.ClassName').show();
Now instead of having onclick events in the html as you have right now, you just bind them in jquery in the ready() method like so:
$(document).ready(function()
{
$('#idOfDiv').bind('click', function()
{
//do work here in this anonymous callback function
});
});
All of this can be done in a external js file so that will significantly clean up your html code
and put all your javascript logic into one location.
EDIT:
Example applied to your situation
$(document).ready(function()
{
$('#various1').mouseover(function()
{
$('#speech1').show();
});
$('#various1').mouseout(function()
{
$('#speech1').hide();
});
});
If you get crafty and utilize a for loop then you could just append the number to the end of the string that represents the selectors like so
$(document).ready(function()
{
for(var i = 1; i < 7; i++)
{
$('#various' + i).mouseover(function()
{
$('#speech' + i).show();
});
$('#various' + i).mouseout(function()
{
$('#speech' + i).hide();
});
}
});
The mouseout and mouseover functions are just the explicit version of using like so
$('selector').bind('mouseover', function()
{
});
$('selector').bind('mouseout', function()
{
});
Have you looked into using jQuery for this? Also, why does the code need to be inlined?
I would recommend doing something like this: http://jsfiddle.net/4N9ym/2/
Note that I have things inverted here (you would probably want to animate in instead of animating out).

Categories

Resources