I have a webpage that I am working on, and am trying to incorporate some JQuery into it. This project is my first time ever using JQuery, so I could be missing something very simple.
Some Background
I only have one event listener within my JQuery code (aside from the ${document).ready())
I have multiple click event listeners within a separate javascript file.
The JQuery .hover() event stops working (and gets stuck on registering as being hovered over) once any of the separate click events are triggered.
My code
jquery.js
$(document).ready(function() {
$(".inShop").hover(function(){
pop($(this).val());
var divToShow = $(this).parent("p").siblings("div.popup");
divToShow.css({
display: "block",
position: "absolute",
right: ($(this).offset().left - $(this).width() - 240) + "px",
top: ($(this).offset().top) + "px"
});
},
function(){
$("div.popup").hide();
});
});
index.html
<div id="list">
<div class="popup" style="display:none;">
<p id="head"><strong>Info</strong></p>
<p class="iInfo"><a id="effect">Effect: </a><a id="eFill"></a></p>
<p class="iInfo"><a id="owned">Owned: </a><a id="oFill"></a></p>
</div>
<p id="available"></p>
<p id="unavailable"></p>
</div>
script.js
var itemShopTxt = document.getElementById('available');
...
list1 += tBreak + `<input class="inShop" name="cpc" type="button" value="${i.name}: ${price} C" onClick="{shopping(this);}"/>`;
...
itemShopTxt.innerHTML = list1;
What I've tried
click function stops hover function from working - This was promising at first, but my css uses specific properties from the hovered element, so I wouldn't be able to strictly define it
jQuery refresh stops jQuery hover from working - This results in the same issue
This list does not include the links that I opened, read, and deemed irrelevant to my issue
I have included this GIF to better demonstrate what is happening:
I have researched this issue extensively, and used various different key words to try to find my answer, but nothing has worked for me. If I have missed something, please let me know.
JQuery code: How to show a div next to the hovered element with jQuery?
I think you could use event.stopPropagation() or event.preventDefaults()
Related
I want a small picture that acts like a button, to be click-able with a function to change the body background-image. I am a total newbie and I'm trying to learn. The most simple way, I thought, would be to have a div with a background-image.
I have to use unsemantic grid, also.
So I pretty much only have the div with a background image. How do I write this function? I'm sure it's really easy and I've read like 20 threads here but none of them were useful for me
Edit: added my code
#knapp {
height:50px;
width:50px;
background-image:url(http://ingridwu.dmmdmcfatter.com/wp-content/uploads/2015/01/placeholder.png);
background-repeat:no-repeat;
background-size:contain;
position:absolute;
top:90vh;
right:3vw;
}
<div id="knapp" class="grid-10 prefix-90"></div>
Add cursor on the div to appear clickable
#knapp {
cursor: pointer;
}
You could put the new background-image in a new css rule
body.newbg {
background-image:url(path-to-new-background.png);
}
This is body with the old background-image
body {
background-image:url(path-to-old-background.png);
}
and with jquery just add/toggle the class by doing something like that (in $(document).ready()):
$('#knapp').on('click', function(){
$('body').addClass('newbg');
// you could instead do toggleClass if you want for each click to have background switch between old background and new background
});
This is a cleaner approach compared to all the other answers as it separates presentation (css), structure (html) and behavior (javascript).
This is because it doesn't use JavaScript to change style directly. Also it doesn't pollute html with onclick which is also a bad practice.
Here is a plunkr: https://plnkr.co/edit/aiGZmvvi6WWGFs7E9xTp
and here is one with a circular collection of backgrounds (thanks to Kai's idea)
https://plnkr.co/edit/0djmmNM9OOTdfYyvLvUH?p=preview
Create a button with onclick attribute with a function name like replace.
Defined the function in your script like:
function replace() {
document.body.style.backgroundImage = 'url(https://lh6.ggpht.com/8mgTDZXaLMS1JsnF28Tjh6dahHwN1FqcXCVnifkfppmNLqnD-mPBuf9C1sEWhlEbA4s=w300)';
}
Explanation:
You set the style property of the body (using document.body object) to other background-image.
If something is not clear, I will happy to explain.
Working example:
function replace() {
document.body.style.backgroundImage = 'url(https://lh6.ggpht.com/8mgTDZXaLMS1JsnF28Tjh6dahHwN1FqcXCVnifkfppmNLqnD-mPBuf9C1sEWhlEbA4s=w300)';
}
body {
background-image: url(http://www.julienlevesque.net/preview/google-smile-preview.jpg);
}
div {
background:blue;
color:#fff;
float:left;
}
<div onclick="replace()">Replace background-image</div>
This may help you...
$('.yourClassofDiv').click({
$(this).css("background-image",'url("' + URLofIMAGE+ '")')
});
Try using onclick at div#knapp element , set document.body.style.background to url of image file
#knapp {
height:50px;
width:50px;
background-image:url(http://lorempixel.com/50/50);
background-repeat:no-repeat;
background-size:contain;
position:absolute;
top:90vh;
right:3vw;
}
<div id="knapp" class="grid-10 prefix-90" onclick="document.body.style.background = 'url(http://lorempixel.com/'+ window.innerWidth + '/'+ window.innerHeight +') no-repeat'"></div>
here is a simple way in jquery
$(document).ready(function() {
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/detail-requiem.jpg)').css('background-repeat', 'no-repeat');
$('div').css('cursor', 'pointer').click(function() {
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/Requiem-Julien-Levesque.jpg)');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body>
<div style="background-color:yellow">Click Here to change background Image</div>
</body>
Here i will explain the code.
The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s).
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".
Here is what happen in the code.
1.
$(document).ready(function(){
// jQuery methods go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.
2
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/detail-requiem.jpg)').css('background-repeat', 'no-repeat');
getting the body element of your html and set its background-image with .css() action. which i gave it more one action
3
$('div').css('cursor', 'pointer').click(function() {
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/Requiem-Julien-Levesque.jpg)');
});
this is where the change takes place. i got the div to be clicked by $('div') and first gave it an action of changing the mouse to cursor to indicate its clickable and then gave it the click function, where our background-image get changed on click
If I understand the question, you should be able to create a variable in jQuery which is an array of all the string versions of your image urls that you want to use:
var images = ['../images/####','../images/$$$$', 'http://some.other/url.here];
// do this for as many images as you want to cycle through
Like that.
Then you can make a counter variable:
var counter = 0;
and set it to zero.
Next, add the event listener on() to your div like this:
$('#knapp').on('click', function(){
});
Finally, inside your event listener, change the CSS background-image property of the div to one of your images in the array:
// do this inside a document.ready() function
$('#knapp').on('click', function(){
$(this).css('background-image','url("' + images[counter] + '")');
counter++;
});
I hope this helped! Also, remember to increment counter
EDIT ----------------------------------------------------------------
OK, so I totally jumped over something obvious which is the fact that the counter might go too high and access something out of scope. To prevent this add the following inside of your on() listener:
if(counter >= images.length - 1){
counter = 0;
}
EDIT 2 --------------------------------------------------------------
Ok, so I didn't know what exactly you were asking at first, so here is my second answer. Since it seems like what you are actually trying to do is only switch the background image once on click, then you could use something like this:
$(document).ready(function(){
$('#knapp').on('click', function(){
$(this).css('background-image','url("YOUR_NEW_URL_HERE")');
});
});
or you could have it toggle between two images by making two identical classes in CSS (except for the background image) and replacing one with the other using .addClass and .removeClass.
EDIT 3---------------------------------------------------------------
I never thought I would edit this post this many times, but apparently I missed that the body background image should be changed (thanks to comments). My bad and thanks for pointing it out (even if you were talking to someone else).
What I want is fairly simple, and I have two examples for it:
http://janvanderkleijn.nl/
http://studio-laucke-siebein.com/
When looking at these portfolio websites you see it's scroll based websites mainly relying on images. The interactivity I'm looking for is the clicking on an image, resulting in a 'hovering' element over the web page, further elaborating the project with text, images etc.
What I like about it is that you don't have to leave the home-page to look into a project, and it can be closed by either pressing the close button in the top right, or clicked anywhere outside of this element. Especially in Laucke-Sibein's webpage it's nice, that when you scroll far enough down, the element dissappears.
How hard is it to achieve a similar result? How does this function work? I've been looking all afternoon and failed to find something that helped me further.
As mentioned by others there are many jQuery plugins like lightbox, fancybox, etc. that are capable of outputting images and text. Or a jquery-ui dialog box would work.
Alternatively you could create your portfolio items inside div's and show them on click events.
<body>
<div id="project-list">
html showing images from your projects. <br />
<img src="img1.jpg" data-project="project1" />
<img src="img2.jpg" data-project="project2" />
</div>
<div id="project1" class="project">
html displaying <br />
your project 1
</div>
<div id="project2" class="project">
html displaying <br />
your project 2
</div>
</body>
Then css something like:
.project { position: absolute; top: 100px; left: 100px; display: none; }
#project-list.fixed { position: static; }
Then the using jQuery it would look like:
$(function(){
// add click handler to the images
$('#project-list img').click(function(e){
// if a project is visible then just return and let the
// document click handler handle the closing of the project
if($('.project:visible').length > 0){
return;
}
// get the data project attribute which tells you which project to open
var project = $(this).data('project');
$('#' + project).slideDown('slow');
// add the fixed class to the project list so that it doesn't scroll
$('#project-list').addClass('fixed');
// you must have this to keep the click event from bubbling up
// through the DOM and triggering the document click function
// which would close the project as soon as it opens.
e.stopPropagation();
});
$(document).click(function(){
// this closes the project when anything is clicked that doesn't
// have the event.stopPropagation function set.
$('.project').slideUp('slow');
$('#project-list').removeClass('fixed');
});
$('.project').click(function(e){
// you want this so if they click anything in the project it doesn't
// close the project.
e.stopPropagation();
});
});
See a fiddle here http://jsfiddle.net/wdv79yxw/1/
Sounds like you're looking for a modal window. There are tons of jQuery libraries out there, or even pure CSS solutions. A decent one that I've used is jQuery fancybox, which supports videos, iframes, content, a gallery of images. It's very robust.
This is what happen when I press the button "Contacto"
and should be like this
and now I'm using this javascript code
$(function(){
$('a#boton-contacto').on('click',function(e){
e.preventDefault();
var strAncla = $(this).attr('href');
$('body,html').stop(true ,true).animate({
scrollTop: $(strAncla).offset().top - $('nav').height()
}, 500);
});
});
but it made the button stop working, I want to know why, what is wrong?
you can go to my site and try it http://genebi.net I hope you can help me, thanks.
This code from you jQuery:
var strAncla = $(this).attr('href'); is setting strAncla to be "http://genebi.net/#contacto"
And since "http://genebi.net/#contacto" is not a valid selector, there is a javascript error that prevents the code from running.
To solve this, either:
Change your url for the element from:
<a id="boton-contacto" href="http://genebi.net/#contacto">CONTACTO</a>
to <a id="boton-contacto" href="http://genebi.net/#contacto">CONTACTO</a>
or:
2: You could use a data attribute in your link:
<a id="boton-contacto" href="http://genebi.net/#contacto" data-element="#contacto">CONTACTO</a>
and alter your jQuery as follows:
var strAncla = $(this).attr('data-element');
And it will work as you desire.
position: fixed; removes it from the normal flow of the document, and means that it doesn't occupy space. You can fix this without Javascript (and it'll be much less janky). It's a little awkward to work around this, but you can do it by having a blank div underneath it to fill up the space. Let's call it "header-spacer".
<div class="header">
...
</div>
<div class="header-spacer"></div>
And some CSS:
.header-spacer {
height: 70px;
}
I am using jQuery plugin version 3.10 to use custom scrollbars. I have numerous horizontal slides and each uses its own custom scrollbar. I want to include javascript .onclick function that expands text. However, the scrollbar does not appear when I expand the text and it overflows. I am using the following code to select the headings which should have the onclick function (tag "h3", class "click"):
function toggleNext(el) {
var next=el.nextSibling;
while(next.nodeType != 1) next=next.nextSibling;
next.style.display=((next.style.display=="none") ? "block" : "none");
}
function getElementsByTagAndClassName(tag,cname) {
var tags=document.getElementsByTagName(tag);
var cEls=new Array();
for (i=0; i<tags.length; i++) {
var rE = new RegExp("(^|\s)" + cname + "(\s|$)");
if (rE.test(tags[i].className)) {
cEls.push(tags[i]);
}
}
return cEls;
}
function toggleNextByTagAndClassName(tag,cname) {
var ccn="clicker";
clickers=getElementsByTagAndClassName(tag,cname);
for (i=0; i<clickers.length; i++) {
clickers[i].className+=" "+ccn;
clickers[i].onclick=function() {toggleNext(this)}
toggleNext(clickers[i]);
}
}
window.onload=function(){toggleNextByTagAndClassName('h3','click')}
Example of HTML:
<article class="slide" id="lorem">
<div class="inner">
<h3 class="click">Lorem Ipsum</h3>
<div class="content">
<p>Sample text, is sample text, is sample text</p>
</div>
I know from previous research that I've done that I have to call the resize function from niceScroll jQuery plugin, which is as follows.
$(name-of-div).getNiceScroll().resize()
I have tried using the resize function with the name-of-div as content, however this does not yield the expected results. Please help if you can. I am not sure how to implement the two together.
Not sure if understood what's going on but I had a similar problem. Try using the resize() inside a setTimeout.
Note that the "name-of-div" must be the name of the scroll's container.
The jQuery code would looks like:
setTimeout(function(){
$('name-of-div').getNiceScroll().resize()
}, 500);
I used 500 as an example, but if your div's text expand while animate you must use a number greater then your div animation, and of course, the code must execute after all interactions
See the question below. There are two answers and both work for me. Basically, I have applied the second method(See the second answer) suggested there. Because, it works instantly and the first method doesn't seem to work instantly after the div has been resized.
Jquery Nice scroll not working
I have a very large HTML page whereby an enterprise user is displaying thousands of database records as part of a batch-update/validation process.
Within the page I need to add tooltips to many of the elements. Previously we have used the trusty approach of doing this in the <head>:
$("elementID").mouseenter(function(){
// tool tip logic
// goes here
});
The problem is that this is adding tens of thousands of lines of JavaScript and causing massive performance problems. So, I am researching the differences of applying this at element level instead. So rather than having the above code for each element that requires a tooltip, I am declaring a single script block like this:
function ShowTooltip(ctrl, tooltip) {
var o = $(ctrl).offset();
var y = o.top;
var x = o.left;
$("#ttfloat").css({ top: o.top, left: o.left });
$("#ttfloat").html(tooltip);
$("#ttfloat").show();
}
function HideToolTip() {
$("#ttfloat").hide();
}
And then firing this using the following approach for each respective element:
<div id="ttfloat"> </div>
<p>Tool tip <span id="lbl1" runat="server" onmouseover="ShowTooltip(this, 'Tip Text');" onmouseout="HideToolTip();">appears here</span></p>
The problem is that when hovering over the <span> elements, there is a flicker of the tooltip element as the browser fires onmouseover repeatedly. I read on other SO solutions that JQuery mouseenter is the way to go to solve this, but can only find examples that wire up the events in the head. Can it be done in-line in the element, or is there a better way altogether? The solution must work with older browsers and be standards compliant.
See JSFiddle
How about something like this:
<span data-tooltip-text="Tip text here">blah blah</span>
And then:
$("[data-tooltip-text]").on({
mouseenter : function() {
var o = $(this).offset();
var tooltip = $(this).attr("data-tooltip-text");
$("#ttfloat").css({ top: o.top, left: o.left })
.html(tooltip)
.show();
},
mouseleave : function() {
$("#ttfloat").hide();
}
});
Demo: http://jsfiddle.net/szCU2/2/
I'd suggest you offset the vertical position of the tooltip a little bit, so that it doesn't completely cover the element that you're hovering over (which is clunky looking, and can potentially cause a mouseleave event since the mouse is then over the tooltip):
o.top + 18; // or whatever offset works for you
Demo: http://jsfiddle.net/szCU2/3/
If the behavior is the same in all of them, you should use a class selector instead of an id selector and simply add that class to all of your divs. Then you just need that code once rather than having a copy of it for every single div. Store the data somewhere useful (like a custom attribute for the div) and use that in your code.
html:
<div id="blah" class="divWithTooltip" data-custom-attribute="some tooltip text">
javascript:
$('.divWithTooltip')
.on('mouseenter', function() {
someMethodToDoYourTooltipStuff( $(this).attr('data-custom-attribute') );
})
.on('mouseout', function() {
someMethodToHideYourTooltip();
});