JQuery failed to change image SRC onmouseover/hover - javascript

After some research, the below code should works fine to change the image source but it's not?
$("#li_1").mouseover(function () {
$(this).attr("src", "images/hover_12.png");
}, function () {
$(this).attr("src", "images/ori_12.png");
});
HTML Code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="demo.css">
<style>
li{
display: block;
}
</style>
</head>
<body>
<div id='wrap'>
<div id="clickable_div">MENU</div>
<div id="nav_menu">
<ul class="dropDown">
<li id="li_1"><img src="images/ori_12.png"></li>
<li id="li_2"><img src="images/ori_14.png"></li>
<li id="li_3"><img src="images/ori_15.png"></li>
<li id="li_4"><img src="images/ori_16.png"></li>
</ul>
</div>
</div>
</div>
</body>
<script>
$("#li_1").mouseover(function () {
$(this).attr("src", "images/hover_12.png");
}, function () {
$(this).attr("src", "images/ori_12.png");
});
$('#wrap').mouseover( function(){
$('#nav_menu').slideDown();
});
$('#wrap').mouseleave( function(){
$('#nav_menu').slideUp();
});
</script>
</html>
DEMO.CSS:
#clickable_div {width:166px; background-color:#9c9c9c;}
*{margin:0; padding:0}
#nav_menu{width:166px; height:auto; background-color:#CCC;display:none;}
#wrap{ width:166px }
The idea is very simple. I'm trying to mouseover an element and have a dropdown feel to list the items, and for each item I hover, the image of li will be replaced.

You seem to be trying to change the src of the LI element, not the IMG element.
You will also need a mouseout event to change the image src back to normal.
Try this:
$("#li_1 img")
.mouseover(function () {
$(this).attr("src", "images/hover_12.png");
})
.mouseout(function () {
$(this).attr("src", "images/ori_12.png");
});
If you want it dynamic, so you don't have to add a block of code for each image, try this.
$('#nav_menu li img')
.mouseover(function () {
this.src = this.src.replace('/ori_', '/hover_');
})
.mouseout(function () {
this.src = this.src.replace('/hover_', '/ori_');
});

Related

How can I toggle JS .text

I have this function that shows the ALT of an image on img click. How can I toggle this function and hide the #show when there will be a Self.close click that hides the lightbox?
$("img").on("click", function() {
$("#show").text($(this).attr("alt"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show"></div>
<img src="https://blogs-images.forbes.com/ericsavitz/files/2011/03/smiley-face.jpg" alt="SMILE">
Thanks in advance.
A simple solution:
$("img").on("click", function() {
var alt = $(this).attr("alt");
$("#show").text($("#show").text() === alt ? '' : alt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show"></div>
<img src="https://blogs-images.forbes.com/ericsavitz/files/2011/03/smiley-face.jpg" alt="SMILE">
You need to keep track of which state it's currently in. There's a number of ways of doing this but this is likely the easiest:
var isShowingText = false;
$("img").on("click", function() {
if (isShowingText) {
$('#show').text('');
} else {
$("#show").text($(this).attr("alt"));
}
// Toggle the flag. false becomes true, true becomes false
isShowingText = !isShowingText;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show"></div>
<img src="https://blogs-images.forbes.com/ericsavitz/files/2011/03/smiley-face.jpg" alt="SMILE">
You could do this by setting the text to nothing if it is filled using:
$('#show').text('');
Example:
$('img').on('click', function () {
$('#show').text($('#show').text() === '' ? $(this).attr('alt') : '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show"></div>
<img src="https://blogs-images.forbes.com/ericsavitz/files/2011/03/smiley-face.jpg" alt="SMILE">
EDIT:
Another solution might be to toggle a CSS class:
// Set the alt text
$('span').text($(this).attr('alt'));
$('img').on('click', function () {
$('span').toggleClass('hide');
});
.span {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="hide"></span>
<img src="https://blogs-images.forbes.com/ericsavitz/files/2011/03/smiley-face.jpg" alt="SMILE">

Clone working for an element but not for entire div

Explanation: I am trying to clone elements / div. I am trying to achieve it by right clicking on them opening up a context menu and clicking on "clone" option.
I have a very simple code, let me show you -
(function ($, window) {
$.fn.contextMenu = function (settings) {
return this.each(function () {
// Open context menu
$(this).on("contextmenu", function (e) {
// return native menu if pressing control
if (e.ctrlKey) return;
//open menu
var $menu = $(settings.menuSelector)
.data("invokedOn", $(e.target))
.show()
.css({
position: "absolute",
left: getMenuPosition(e.clientX, 'width', 'scrollLeft'),
top: getMenuPosition(e.clientY, 'height', 'scrollTop')
})
.off('click')
.on('click', 'a', function (e) {
$menu.hide();
var $invokedOn = $menu.data("invokedOn");
var $selectedMenu = $(e.target);
settings.menuSelected.call(this, $invokedOn, $selectedMenu);
});
return false;
});
//make sure menu closes on any click
$('body').click(function () {
$(settings.menuSelector).hide();
});
});
function getMenuPosition(mouse, direction, scrollDir) {
var win = $(window)[direction](),
scroll = $(window)[scrollDir](),
menu = $(settings.menuSelector)[direction](),
position = mouse + scroll;
// opening menu would pass the side of the page
if (mouse + menu > win && menu < mouse)
position -= menu;
return position;
}
};
})(jQuery, window);
$("#container").contextMenu({
menuSelector: "#contextMenu",
menuSelected: function (invokedOn, selectedMenu) {
var msg = "You selected the menu item '" + selectedMenu.text() +
"' on the value '" + invokedOn.text() + "'";
//var itsId = $(invokedOn).attr('id');
var selectedText = $(invokedOn).get(0).outerHTML;
var parentDiv = $(invokedOn).parent();
alert(selectedText);
if (selectedMenu.text() == "Clone"){
//alert("inside");
$(invokedOn).clone().insertAfter(invokedOn);
}
}
});
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">
</head>
<body>
<div id="container">
<div id="content">content</div>
<div id="content2">
<p>This is p </p>
<h3> This is h3 </h3>
</div>
</div>
<ul id="contextMenu" class="dropdown-menu" role="menu" style="display:none" >
<li><a tabindex="-1" href="#">Clone</a></li>
<li><a tabindex="-1" href="#">Another action</a></li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="contextmenu.js"></script>
</body>
Run the code and Right click on "this is p" or "this is h3" and select clone, they will be cloned but i also want to clone entire div according to my selection. This requirement works for me on click but dont know how to do it by context menu, see this code here, the below code will work with left click, see this pic, i can clone entire div or single element depending on my area of click, same thing i want above with right click - https://www.dropbox.com/s/mqftyt96s75jc6b/Screenshot%202017-04-07%2013.38.30.png?dl=0
$('*').on('click', function(e){
e.stopPropagation()
var thisDiv_name = $(this).attr('id');
var thisDiv = $(this);
var parentDiv = $(this).parent();
// $(this).clone().appendTo(parentDiv);
$(this).attr('style','outline: #6c6b69 solid thin;');
$(this).clone().insertAfter(thisDiv);
//alert($(this).html());
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>
<div id="main">
<div id="content">content</div>
<div id="content2">
<p>This is p </p>
<h3> This is h3 </h3>
</div>
<button id="button">show it</button>
</div>
</body>
</html>
To achieve this you could implement a new context menu item which clones the parent() element of one which triggered the event.
Also note that you can tidy up the logic by using a data attribute to specify the action to be performed instead of matching the text. Try this:
!function(a,b){a.fn.contextMenu=function(c){function d(d,e,f){var g=a(b)[e](),h=a(b)[f](),i=a(c.menuSelector)[e](),j=d+h;return d+i>g&&i<d&&(j-=i),j}return this.each(function(){a(this).on("contextmenu",function(b){if(!b.ctrlKey){var e=a(c.menuSelector).data("invokedOn",a(b.target)).show().css({position:"absolute",left:d(b.clientX,"width","scrollLeft"),top:d(b.clientY,"height","scrollTop")}).off("click").on("click","a",function(b){e.hide();var d=e.data("invokedOn"),f=a(b.target);c.menuSelected.call(this,d,f)});return!1}}),a("body").click(function(){a(c.menuSelector).hide()})})}}(jQuery,window);
$("#container").contextMenu({
menuSelector: "#contextMenu",
menuSelected: function($invokedOn, $selectedMenu) {
var action = $selectedMenu.data('action');
switch (action) {
case 'cloneEl':
$invokedOn.clone().insertAfter($invokedOn);
break;
case 'cloneParent':
var $parent = $invokedOn.parent();
$parent.clone().insertAfter($parent);
}
}
});
/* CSS is only to make the output more obvious */
p { background-color: #CC0; }
h3 { background-color: #0CC; }
#container > div {
border: 1px solid #C00;
margin: 5px;
}
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div id="container">
<div id="content">content</div>
<div id="content2">
<p>This is p </p>
<h3>This is h3</h3>
</div>
</div>
<ul id="contextMenu" class="dropdown-menu" role="menu" style="display:none">
<li><a tabindex="-1" href="#" data-action="cloneEl">Clone</a></li>
<li><a tabindex="-1" href="#" data-action="cloneParent">Clone parent</a></li>
<li><a tabindex="-1" href="#" data-action="another">Another action</a></li>
</ul>

Event when a pair of elements are clicked

I have 5 elements with class .home and unique id's, and a button with class .btn1. When .home is clicked after .btn1 and vice versa, a function should be executed. I don't know what jQuery method i should use.
Try this :
<!DOCTYPE html>
<html>
<head>
<style>
.active {
background-color: skyblue;
}
</style>
</head>
<body>
<div class="home">I am Div1</div>
<div class="home">I am Div2</div>
<div class="home">I am Div3</div>
<div class="home">I am Div4</div>
<div class="home">I am Div5</div>
<button class="btn">Run</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var divReady = false;
var btnReady = false;
$(".btn").on("click",function(){
btnReady = true;
$(this).addClass("active");
if (divReady)
fun();
})
$("div").on("click",function(){
divReady = true;
$("div").removeClass("active");
$(this).addClass("active");
if (btnReady)
fun();
})
function fun() {
alert("I am working!")
$(".btn,div").removeClass("active");
btnReady = false;
divReady = false;
}
})
</script>
</body>
</html>
I don't think there's a specific jQuery trick for that.
Why not use classes to store state?
$(function() {
$(".home").click(function () {
$(this).addClass("active");
if ($(".btn1").hasClass("active")) {
console.log("Doing something");
}
});
$(".btn1").click(function () {
$(this).addClass("active");
if ($(".home").hasClass("active")) {
console.log("Doing something");
}
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
<button class = 'btn1' >Button</button>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
Simply count the times an event occured, and store the events. That can be easily done with an Array:
//create an array to store events
events=[];
//create a handler function
function handler(event){
//add the event to our array
events.push(event);
if(events.length==2){
//two events fired:
//first event:
a=events[0];
//second:
b=events[1];
//do whatever
}
}
//add an eventlistener that calls our handler and passes 'documentclick'
document.addEventListener("documentclick",function(){handler("click")});

when a div is showing do some thing for me and when its hidden stop that , with jquery its possible?

How i can write if #menu-drop display:block, add class to #header. else remove class from #header and follow other codes.
Thanks.
in CSS file #menu-drop {display:none}; and follow my jQuery codes it will show with slideDown event.
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(document).on("click","#menu-oc",function() {
jQuery("#menu-drop").slideToggle("slow");
});
jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() > 0) {
jQuery("#header").addClass("fixed");
jQuery("#header").addClass("goblack");
} else {
jQuery("#header").removeClass("fixed");
jQuery("#header").removeClass("goblack");
}
});
jQuery("#introcenter").animate({width: "0"},600,function (){
jQuery(".intro").animate({height : "0"},600,function () {
jQuery("#main").animate({opacity : "1"},500);
});
});
});
</script>
<body>
<div id="header">
<button id="menu-oc">HELLO</button>
</div>
<div id="menu-drop">
<div id="menu">
<jdoc:include type="modules" name="menu" style="html" />
</div>
</div>
<body>
change your JS code like this -
jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() > 0 && (jQuery('#menu-drop').css('display') == 'none')) {
jQuery("#header").addClass("fixed");
jQuery("#header").addClass("goblack");
} else {
jQuery("#header").removeClass("fixed");
jQuery("#header").removeClass("goblack");
}
});
and then add inline style to your #menu-drop
display: none;
check this fiddle you will see the #menu-drop is displaying and the #header is not going border-color: black;
now check this fiddle, here you will see I have added an inline style display: none to #menu-drop and in this case the #header is going black!!
I think what you are looking for are jquery is-function and :visible-selector.
For example:
var $header = $("#header");
if ($("#menu-drop").is(":visible")) {
$header.addClass("myClass");
}
else
{
$header.removeClass("myClass");
}

JS JQUERY bug when expanding ul event of click on li doesnt work

I've created a simple web page to learn about JQuery, But whenever I click on Button: another one its making the event of click on li disappear, glitched, it does nothing when the li is clicked.. . Here is the code:
JS:
$(document).ready(function(){
console.log("Ready");
var toggle = 0;
$("li").on("click",function(){
console.log("Clicked on li");
try{
$(this).hide(800);
$(this).removeClass("con");
$(this).addClass("con");
}
catch(err){
console.log("Exception "+err.message);
}
});
$("input").on("focus",function(){
console.log("Focused on input");
$("li").hide(800);
$("#D").html("Open div");
toggle = 1;
});
$("input").on("focusout",function(){
console.log("FocusedOut on input");
$("li").html($("input").val());
$("li").show(500,function(){
$("#D").html("Close div");
toggle = 0;
});
});
$("button").on("click",function(){
console.log("Clicked button :"+$(this).html());
if($(this).attr("id")=="s"){
$("li").show(300);
}
else if($(this).attr("id")=="n"){
$("li").removeClass("con");
}
else if($(this).attr("id")=="C"){
$("li").addClass("con");
}
else if($(this).attr("id")=="an"){
console.log("Added to html : "+$(".uDefined").html()+"<br/><li>"+$("li").last().html().substring(0,7)+($("li").last().html().substring(7,8)-(1)+1+1)+"</li>");
$(".uDefined").html($(".uDefined").html()+"<br/><li>"+$("li").last().html().substring(0,7)+($("li").last().html().substring(7,8)-(1)+1+1)+"</li>");
}
else{
$(".list").slideToggle(1000,function(){
if(toggle==0){
$("#D").html("Open div");
toggle=1;
}
else{
$("#D").html("Close div");
toggle = 0;
}
});
}
});
});
HTML:
<html>
<style type="text/css">
.list{
font-size: 100;
background-color: white;
}
li{
margin-left: 100;
border-radius: 20;
border-width: 3;
background-color: Black;
color:White;
}
.con{
color:red;
}
.uDefined{
}
</style>
<body onload="" style="background-color:gray;margin:40" >
<title>JQuery TryOut</title>
<h3 style="margin-left:800;">Welcome</h3>
<button id="D">Close Div</button>
<button id="s">Show All</button>
<button id="n">Remove Classes</button>
<button id="C">Add Classes</button>
<div class="list">
<ul class="uDefined">
<li class="con">content1</li>
<li>content2</li>
<li>content3</li>
<li>content4</li>
<li>content5</li>
<li>content6</li>
</ul>
</div>
<div>
<p>Please focus on this text box:</p><input id="ttt" placeholder="Enter text here" value="" type="text" />
</div>
<button id="an" >another one</button>
</body>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="JavaScript.js"></script>
THANKS FOR HELPERS!
Direct events are only attached to elements (that exist) at the time the .on() method is called. So when you are adding buttons dynamically, you need to use delegated event handlers.
You should change your code like this:
$("ul").on("click", "li", function () {
...
});
More about delegated events:
http://learn.jquery.com/events/event-delegation/

Categories