Javascript - Change src at onmouseover and onmouseout - javascript

I want to do that onmouseover change the image and onmouseout it returns the default image. I use this code:
<div class="home-social-share">
<div style="margin-right:15px;width:11px;float:left;">
<a href="javascript:void(0)" onclick="window.open('http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php the_title(); ?>','Condividi su Facebook','height=300, width=750,scrollbars=no, resizable=yes')">
<img src="http://www.primapaginaonline.it/wp-content/themes/pponline/images/fbshareoff.png" alt="Condividi su Facebook" title="Condividi su Facebook" onmouseover="this.src='http://www.primapaginaonline.it/wp-content/themes/pponline/images/fbshare.png'" onmouseout="this.src='http://www.primapaginaonline.it/wp-content/themes/pponline/images/fbshareoff.png'">
</a>
</div>
<div style="float:left;margin-right:15px;">
<a href="javascript:void(0)" onclick="window.open('http://twitter.com/share?text=<?php the_title(); ?> • Prima Pagina Online&url=<?php the_permalink(); ?>','Condividi su Twitter','height=300, width=500,scrollbars=no, resizable=yes')">
<img src="http://www.primapaginaonline.it/wp-content/themes/pponline/images/tt-shareoff.png" alt="Condividi su Twitter" title="Condividi su Twitter" onmouseover="this.src='http://www.primapaginaonline.it/wp-content/themes/pponline/images/tt-share.png'" onmouseout="this.src='http://www.primapaginaonline.it/wp-content/themes/pponline/images/tt-shareoff.png'" />
</a>
</div>
<div style="float:left;">
<a href="<?php the_permalink();?>/#disqus_thread">
<img src="http://www.primapaginaonline.it/wp-content/themes/pponline/images/pencil-off.png" alt="Commenta l'articolo" title="Scrivi un commento sull'articolo" onmouseover="this.src='http://www.primapaginaonline.it/wp-content/themes/pponline/images/pencil.png'" onmouseout="this.src='http://www.primapaginaonline.it/wp-content/themes/pponline/images/pencil-off.png'" />
</a>
</div>
Now, it works the onclick functions but the images remains the same, so the onmouseover and onmouseout doesn't work.
Thanks

I'm unsure whether your using Jquery or not, so I'll include examples of both.
<img id="change" src="picture" alt="picture.jpg">
Jquery -
$('#change').on("mouseenter", function() {
$(this).attr('src', 'picture2');
}).on("mouseleave", function() {
$(this).attr('src', 'picture');
});
Javascript -
document.getElementById('change').addEventListener("onmouseover", function() {
this.src = 'picture2';
}).addEventListener("onmouseout", function() {
this.src = 'picture';
});
That should get you going!

Use the onmouseover and onmouseout events because it always works.
Example:
<img src="picture" onmouseover="this.src='picture2'" onmouseout="this.src='picture3'">
Also see http://helplogger.blogspot.be/2012/05/create-rollover-image-effect-change.html

The code from your jsfiddle and the one from your website have some differences.
This code is from your website:
<img src="http://www.primapaginaonline.it/wp-content/themes/pponline/images/pencil-off.png?b33912" alt="Commenta l'articolo" title="Scrivi un commento sull'articolo" onmouseover="this.src=" http:="" www.primapaginaonline.it="" wp-content="" themes="" pponline="" images="" pencil.png?b33912""="" onmouseout="this.src=" pencil-off.png?b33912""="">
This is easy to get lost with all this code in a simple tag but if you look closely you will see some of the problems.
First, you have double quotes inside double quotes:
onmouseout="this.src=" pencil-off.png?b33912""=""
And some of these double quotes are not supposed to be there, ex. http:="" in
onmouseover="this.src=" http:="" www.primapaginaonline.it=""
Clean this up and it will works!

Related

Working with src and alt to replace an image

I have a part in my site that dedicated to changing the language.
Right now, in a circle button, i have united-kingdom flag. This is the default option.
<a class="nav-link-language js-language-trigger">
<img src="http://my-site.test/wp-content/uploads/2018/04/260-united-kingdom.png" alt="">
For example i have an option for German Language
<div class="nav-link-language-holder">
<a><img src="http://my-site.test/wp-content/uploads/2018/04/260-germany.png" alt=""><i>German</i></a>
</div>
How can i set with javscript, when user click on the icon for Germany, it will be replaced for the default option (right now is united-kingdom)
Thanks a lot
Here's a quick way to change your img src :
<img id="Your_IMG_ID" src="olg-img-src.png">
<button onclick="change_img_src()">Change SRC</button>
<script>
function change_img_src() {
document.getElementById("Your_IMG_ID").src = "new-img-src.png";
}
</script>
To generalize what you're looking for and further simplify it, here's a way to do it :
<!--- Your main flag --->
<img id="main-flag" style="cursor:pointer" src="img.png"/>
<!--- Rest of flags --->
<img style="cursor:pointer" onclick="Change_flag(this.src)" src="img.png"/>
<img style="cursor:pointer" onclick="Change_flag(this.src)" src="img-2.png"/>
<img style="cursor:pointer" onclick="Change_flag(this.src)" src="img-3.png"/>
<!----Other flags---->
<script>
function Change_flag(_src) {
document.getElementById("main-flag").src = _src;
}
</script>

JQuery: How to get an element to show up once the user clicks?

I'm new to JQuery. The assignment I have to do is a card game where two players play to beat each other's sum. Anyways I am having trouble with the initial step of getting the game area to show up once the user enters their names and clicks "new game". I was able to successfully hide the game when the page loads, but at the moment when I enter the names and click new game, nothing happens. I prevented defaults and I do have the .show in there in the method as well. Does anyone know how to do this? This is my code so far:
$(document).ready(function(){
$(".GameArea").hide();
GameStart();
});
function GameStart(){
$(".PlayerID").on("button",function(event) {
event.preventDefault();
setupUsers();
turnSetUp();
});
}
function setupUsers(){
Player1Name = document.PlayerName;
Player2Name = document.PlayerName2;
var player1Score = 0;
var player2Score = 0;
var x = [[Player1Name,Player1Score], [Player2Name, Player2Score]];
$(".GameArea").show();
}
function turnSetUp(){
$.post("link.php") //this is a full php address that was provided to me, ignore the link
.done(function (data){
var deck = $.parseJSON(data);
resetListeners();
//deck.Cards[0] is the value to beat
//loop to get the remainder cards from the deck
});
}
function resetListeners(){
$(".GameArea a").on("click", function(fixCard){
//event.preventDefault();
//console.log( $( this ).text() );
});
}
function fixCard(){
}
function calculateCurrentScore(){
}
function EndGame(){
}
This is the Game Area of the html too
<div class="GameArea">
<span id="firstgroup">
<a href="">
<img src="Desktop Cards/desktopCard0.png" alt="0"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard1.png" alt="1"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard2.png" alt="2"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard3.png" alt="3"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard4.png" alt="4"/>
</a>
</span>
<span id="secondgroup">
<a href="">
<img src="Desktop Cards/desktopCard0.png" alt="0"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard1.png" alt="1"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard2.png" alt="2"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard3.png" alt="3"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard4.png" alt="4"/>
</a>
</span>
</div>
I think you may be having an error here in your code.
function GameStart(){
$(".PlayerID").on("button",function(event) {
event.preventDefault();
setupUsers();
turnSetUp();
});
}
when using the jquery on function you are saying on "button" which really doesn't mean anything, what we need to do is select the button in the $([button id]) and create an on click event. Kind of like this.
$("[id for area to show]").on("click",function(event) {
//code to display game area goes here.
}
In the future I would isolating the issue, or even checking out the developer console on google chrome. The error messages can be easily tracked here, and can let you know what is going wrong.

Incrementing +1 the class in javascript

Hi im doing a PHP loop where I set a class, this loop make a list of items, and each one of them will have a "share" button that will open a window, (div display:none) the javascript open this div, and it works perfect..
My problem is that in this moment I have inserted the <script> code inside the loop so each item has its own <script></script> code...
Is there any way to do just one and take that code out of the php loop, so I can improve the code.
<script>
$('a.sharebtnc').click(
function(event) {
event.stopPropagation();
$('div.redescompartir').fadeToggle(300);
}
);
</script>
In the Loop well I just add to the class the id like this (id :32 )
<script>
$('a.sharebtnc32').click(
function(event) {
event.stopPropagation();
$('div.redescompartir32').fadeToggle(300);
}
);
</script>
How can I make this script works for all elements no matter the id number, I have no idea, but I know this is the correct way of doing this , right?
The HTML is very simple, its the same for each item... I mean each item has its own div with for <a href="" > </a> elements
<a href="#" class="sharebtnc(id)">
<div class="redescompartir(id)">
<a href="" >Twitter </a>
<a href="" >Facebook </a>
<a href="" >Google </a>
<a href="" >Foursquare </a>
</div>
Add a new class and attribute to the input element like
instead of
<a class="sharebtnc32" />
use
<a class="sharebtnc sharebtnc32" data-id="32"/>
then
jQuery(function ($) {
$('.sharebtnctl').click(function (event) {
event.stopPropagation();
$('.redesopenclose' + $(this).data('id')).fadeToggle(300);
});
})
My preferred method: PHP to generate link between the two elements, then a small snippet of JS to grab which particular one was clicked.
PHP:
$num = 100;
for ($x = 0; $x < $numItems; $x++) {
echo "
<a href='#' class='sharebtn' target='$x'>Share</a>
<div class='redescompartir' id='$x'>
<a href=''>Twitter</a>
<a href=''>Facebook</a>
<a href=''>Google</a>
<a href=''>Foursquare</a>
</div>
";
}
HTML output:
<a href="#" class="sharebtn" target='32'>Share</a>
<div class="redescompartir" id='32'>
<a href="" >Twitter </a>
<a href="" >Facebook </a>
<a href="" >Google </a>
<a href="" >Foursquare </a>
</div>
JS:
$('a.sharebtn').on('click', function(e) {
e.stopPropagation();
var target = $(e.currentTarget).attr('target');
$('#'+target).fadeToggle(300);
});
This way you only need a single <script></script> tag, which your user's broswers will thank you for. :)

Mouse Hover effect runs on each item

I have 5 occurence of UL on a single page. So , when i mouse-over one image then the same effect runs of every instance of UL(i.e. it changes the HTML of all 5 occurences).
I want to execute the script on individual UL so that the effect runs on the respective UL where i mouse-hover instead of all of them.
Live code example : http://jsfiddle.net/5FPSc/
Thanks in advance. Any help / pointer would be of great help. / GSA
HTML :
<ul class="answerOptions">
<li data-score="0" data-answer="A" class="answer-1">
<figure><img src="assets/images/styles/quiz/ques2_A.jpg" alt="" title="" />
<figcaption>Dinner and a movie</figcaption>
</figure>
</li>
<li data-score="1" data-answer="B" class="answer-2">
<figure><img src="assets/images/styles/quiz/ques2_B.jpg" alt="" title="" />
<figcaption>2 words: Laser Tag</figcaption>
</figure>
</li>
<li data-score="0" data-answer="C" class="answer-3">
<figure><img src="assets/images/styles/quiz/ques2_C.jpg" alt="" title="" />
<figcaption>Stroll through the park and a picnic</figcaption>
</figure>
</li>
<li data-score="0" data-answer="D" class="answer-4">
<figure><img src="assets/images/styles/quiz/ques2_D.jpg" alt="" title="" />
<figcaption>Skydiving</figcaption>
</figure>
</li>
<li data-score="4" data-answer="E" class="answer-5">
<figure><img src="assets/images/styles/quiz/ques2_E.jpg" alt="" title="" />
<figcaption>Art gallery and wine tasting</figcaption>
</figure>
</li>
</ul>
<div class="answerItem-1"></div>
SCRIPT :
$('.answerOptions figure').hover(function(){
$(".answerItem-1").html($(this).find("figcaption").html());
},function(){
if($('figure').hasClass('selected') != true){
$(".answerItem-1").html("");
}
else {
$(".answerItem-1").html($("figure.selected").find("figcaption").html());
}
});
$('.answerOptions figure').click(function(){
$('figure').removeClass('selected');
$(this).addClass("selected");
$(".answerItem-1").html($(this).find("figcaption").html());
});
Dont use class, use Id. class hover efects runs on all items, id can be only one on page.
The reason they are all "popping up" is because of this line: $(".answerItem-1") you're selecting EACH and every .answerItem-1 and you have a bunch of those.
You'd need to set unique identifiers. I would do something like this:
<figure rel="q1">
...
<div id="q1" class="answerItem-1"></div>
//jquery code
var q = $(this).attr('rel');
$('#'+q).html($(this).find("figcaption").html());
http://jsfiddle.net/5FPSc/4/
I think you should use objective concept, that make the LI tag has own event handler.
Just take a look to below scripts and kindly be a reference to your codes.
$('ul.answerOptions').delegate('li.answer-1', 'hover', function(event) {
if (event.type == 'mouseenter') {
console.log('inbound');
var $target = $(this).parents('div.question').find('div.answerItem-1');
var showText = '';
showText = $(this).find('figcaption').html();
$target.html(showText);
} else if (event.type == 'mouseleave') {
var $target = $(this).parents('div.question').find('div.answerItem-1');
$target.html('');
}
});​

How to condense and call each function in a for loop or if statement under one larger function?

<html>
<head>
<link rel="stylesheet" href="css/general.css" />
<link id="style_replace" rel="stylesheet" href="css/default.css" />
<script type="text/javascript" src="js/jquery-1.5.min.js"></script>
<style type="text/css">.pretty { color:pink; }</style>
<script type="text/javascript">
function showApple(bakedGood)
{
$("#applepie_off, .apple_description").show();
$("#applepie_on").hide();
}
function hideApple(bakedGood)
{
$("#applepie_off, .apple_description").hide();
$("#applepie_on").show();
}
function showBanana(bakedGood)
{
$("#banana_off, .banana_description").show();
$("#banana_on").hide();
}
function hideBanana(bakedGood)
{
$("#banana_off, .banana_description").hide();
$("#banana_on").show();
}
function showCarrot(bakedGood)
{
$("#carrot_off, .carrot_description").show();
$("#carrot_on").hide();
}
function hideCarrot(bakedGood)
{
$("#carrot_off, .carrot_description").hide();
$("#carrot_on").show();
}
function showCookie(bakedGood)
{
$("#cookie_off, .cookie_description").show();
$("#cookie_on").hide();
}
function hideCookie(bakedGood)
{
$("#cookie_off, .cookie_description").hide();
$("#cookie_on").show();
}
function changeStyleSheet(styleName)
{
$("#style_replace").attr("href", "css/" + styleName + ".css");
}
$(function()
{
$(".contract, .apple_description, .banana_description, .carrot_description, .cookie_description").hide();
});
</script>
Original
Larger Text
<h1>Recepie List</h1>
<div id="list">
<div id="apple_pie" class="recepie">
<h3>Apple Pie</h3>
<a class="expand" id="applepie_on" href="#" onClick="showApple()">expand</a>
<a class="contract" href="#" id="applepie_off" onClick="hideApple()">contract</a>
<img class="desert_img" src="images/apple_pie.jpg" />
<p class="apple_description">
This was my grandmother's apple pie recipe. <br />
I have never seen another one quite like it. <br />
It will always be my favorite and has won me <br />
several first place prizes in local competitions. <br />
I hope it becomes one of your favorites as well!
</p>
</div>
<div id="banana_bread" class="recepie">
<h3>Banana Bread</h3>
<a class="expand" id="banana_on" href="#" onClick="showBanana('banana_bread')">expand</a>
<a class="contract" id="banana_off" href="#" onClick="hideBanana('banana_bread')">contract</a>
<img class="desert_img" src="images/banana_bread.jpg" />
<p class="banana_description">
Why compromise the banana flavor? This banana <br />
bread is moist and delicious with loads of <br />
banana flavor! Friends and family love my recipe <br />
and say it's by far the best! It's wonderful toasted!! Enjoy!
</p>
</div>
<div id="carrott_cake" class="recepie">
<h3>Carrott Cake</h3>
<a class="expand" id="carrot_on" href="#" onClick="showCarrot('carrot_cake')">expand</a>
<a class="contract" id="carrot_off" href="#" onClick="hideCarrot('carrot_cake')">contract</a>
<img class="desert_img" src="images/carrott_cake.jpg" />
<p class="carrot_description">
Why compromise the banana flavor? This banana <br />
bread is moist and delicious with loads of <br />
banana flavor! Friends and family love my recipe <br />
and say it's by far the best! It's wonderful toasted!! Enjoy!
</p>
</div>
<div id="holiday_cookies" class="recepie">
<h3>Holiday Cookies</h3>
<a class="expand" id="cookie_on" href="#" onClick="showCookie('holiday_cookies')">expand</a>
<a class="contract" id="cookie_off" href="#" onClick="hideCookie('holiday_cookies')">contract</a>
<img class="desert_img" src="images/holiday_cookies.jpg" />
<p class="cookie_description">
This is an old family recipe that makes a very <br />
delicious cookie.
</p>
</div>
</div>
function showMyStuff(name,what) {
if(what) {
$("#"+name+"_off, ."+name+"_description").show();
$("#"+name+"_on").hide();
}
else {
$("#"+name+"_off, ."+name+"_description").hide();
$("#"+name+"_on").show();
}
}
usage:
showMyStuff("carrot",true) // this equals to the showCarrot();
showMyStuff("carrot",false) // this equals to the hideCarrot();
This can be greatly simplified
$(function() {
$(".contract, [class$='_description']").hide();
$("a[id$='_on']").click(function(e){
e.preventDefault();
$(this).siblings(":not(img,h3)").add(this).toggle();
});
$("a[id$='_off']").click(function(e){
e.preventDefault();
$(this).siblings(":not(img,h3)").add(this).toggle();
});
});
I used the ends with [$=''] attribute selector, the not selector :not() selector, and the add add() traverser. Since you're using jQuery you don't have to inline bind your onclick events, use a click event binder.
The click event finds all of the siblings of the clicked element except h3 and img tags and calls toggle() which shows it if it is hidden and hides it if it is shown.
working example: http://jsfiddle.net/hunter/SPtqW/
See example of the following here.
First, I've removed your onclick handlers from your HTML and placed them inside the jQuery instead.
Then in the click functions I've used the methods next(), prev() and nextAll() to help find the appropriate elements to show and hide. See http://api.jquery.com/ for more information on these methods.
$('.expand').click(function(e){
e.preventDefault();
$this = $(this);
$this.nextAll('p').first().show();
$this.next('.contract').show();
$this.hide();
});
$('.contract').click(function(e){
e.preventDefault();
$this = $(this);
$this.nextAll('p').first().hide();
$this.prev('.expand').show();
$this.hide();
});
See example.
It looks like you're attempting to create an accordion style interface. If so, you might want to take a look at the accordion widget that's a part of JQuery UI:
http://jqueryui.com/demos/accordion/
And if you want to focus your changes on the "Description" and "Button", you can change the #hunter's answer with:
$(this).siblings(".expand, [class$='_description']").add(this).toggle();
And
$(this).siblings(".contract, [class$='_description']").add(this).toggle();
Here is a fork of #Hunter's Fiddle, with these modification : http://jsfiddle.net/akarun/FTRHQ/

Categories