How to make specific click trigger link else do something else? - javascript

I am doing this for a "welcome dialog".
This function listens if you click on specific <div> and sends you to another web page or closes the welcome <div>.
But I think I couldn't make it work for the "close" functionality.
My script in the HTML head:
function hideWell() {
if (("welSolu").on('click hover')) {
location.href = "http://www.cnn.com";
}
document.getElementById("welScreen").style.visibility = "hidden";
document.getElementById("welScreen").style.display = "none";
document.querySelector("html").style.overflow = "visible";
}
My <div>s in the HTML body:
<div id="welScreen" onmousedown="hideWell()">
<div id="welSolu">to go another page click here</div>
</div>

I suggest you to use two different functions for that, because it is a good practice that one function does one thing. Event your code has several mistakes, without jquery you can do your thing like this:
function doRedirect(e) {
// Prevent event propagation to the outer div
e.stopPropagation();
// Do your redirect
console.info("redirect");
}
function hideWell(e) {
// Do the hiding thing
console.info("hideWell");
}
#welScreen {
padding: 15px;
background: gray;
}
#welSolu {
background: green;
}
<div id="welScreen" onmousedown="hideWell(event)">
<div id="welSolu" onmousedown="doRedirect(event)">to go another page click here</div>
</div>

There is no need to attach a function to the onmousedown event. Just set up event listeners for whatever you want. I'm not entirely sure when you want to hide the welcome div, but something like this should work:
$('#welSolu').click(function() {
location.href = "http://www.cnn.com";
});
$('#welScreen').click(function() {
this.hide();
});
HTML:
<div id="welScreen">
<div id="welSolu">to go another page click here</div>
</div>

The problem in your code is in the if clause - the on() method in JQuery uses callback mechanism - its not something you call to "check the status", instead you use it to "register for status change notifications".
So something like this is the intended behavior:
$("#welSolu").on('click hover', function() {
location.href = "http://www.cnn.com";
});
(although changing the current page when someone hovers over an element in the page is really disruptive, please don't do that).
This code shouldn't be inside the hideWell() function - it should be run as part of the ready state handling of your page - i.e. it should be run immediately as the "document becomes ready" but not before that. JQuery has a facility for that, which would look something like this:
$(document).ready(function(){
$("#welSolu").on('click hover', function() {
location.href = "http://www.cnn.com";
});
});
The other part of the function can stay the same as it is and it will get activated as you expect when the user "mouses down" on the part of the div that wasn't handled by the JQuery event handler - though it is likely a good idea to also change that to use JQuery event handling, just to make all the code use the same mechanism: its easier to understand and maintain that way.
So the full replacement code might looks like this:
Script in HEAD:
$(document).ready(function() {
$("#welSolu").on('click hover', function() {
location.href = "http://www.cnn.com";
});
$("#welScreen").on('click', function() {
document.getElementById("welScreen").style.visibility = "hidden";
document.getElementById("welScreen").style.display = "none";
document.querySelector("html").style.overflow = "visible";
});
}

Related

Activate hover action on a certain word

Okay, so this is something that has already been done so I know it's possible. What I'd like is that, when the user hovers the mouse on some word defined by the wordHoverAssign() function, something would get activated.
So, in a more concise manner: When the page is loaded the text I love potatoes! shows up on screen, created with HTML. Then the function wordHoverAssign("potatoes") is executed. What should happen then, when I hover the word potatoes, is that an alert message would pop up with, for example, this message You hovered the word!.
Is this possible? How would I go about doing it? I'd really like it if I didn't have to use any more frameworks/plugins. I'm using jQuery by the way.
Thank you.
My code so far (if you don't feel like setting it up):
wordHoverAssign("potatoes");
function wordHoverAssign(theWord) {
//code here
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>I love potatoes!</p>
The following allows you to assign different function to any word inside the #content div. The associated function is called only when the specific word is hovered.
<div id="content">
I love potatoes!<br/>
She loves something else<br/>
The potatoes coming again.
</div>
<script>
window.wordsAssigned = {};
function wordHoverAssign(word,func){
wordsAssigned[word] = func;
}
wordHoverAssign('potatoes',function(){
alert('Patatoes hovered!');
});
wordHoverAssign('something else',function(){
alert('something else!');
});
$(function(){
var content = $('#content');
var html = content.html();
for(var word in wordsAssigned){
html = html.replace(new RegExp(word,"gm"),'<span onmouseover="wordsAssigned[\''+word+'\']()">'+word+'</span>');
}
content.html(html);
})
</script>
As per your need :contains('text') suits you better. see example:
wordHoverAssign("potatoes");
function wordHoverAssign(theWord) {
$( ":contains("+theWord+")" ).hover(function(){
alert("Hover happend");
})
}
Here is Updated DEMO
But above code will alert twice because of hover event also bind with body, so my suggestion is use special tag. See following snippet:
wordHoverAssign("potatoes");
function wordHoverAssign(theWord) {
$( "p:contains("+theWord+")" ).hover(function(){
alert("Hover happend");
})
}
Another DEMO for hover in p tag. It won't work on body hover.

document.ready() function not executed, works in dev console

I'm trying to simulate a click in a tabbed div when the page loads.
To do this I use:
$(document).ready(function() {
$("#tab_inbox").click();
});
However, this doesn't seem to work, but when I enter this in the dev console on Google chrome, it does work..
$("#tab_inbox").click();
To show the tabs, I use this code:
$("#tab_inbox").click(function() {
$("#othertab").hide();
$("#tab_inbox").show();
});
Anybody knows what's wrong?
Try this:
$(document).ready(function() {
setTimeout(function () {
$("#tab_inbox").trigger('click'); //do work here
}, 2500);
});
I read in your comment that you're using show/hide techniques and I assume you need the click for an initial display option? If so, hide (or show) your element(s) specifically in the code rather than saying click to hide/show. So
$(document).ready(function() {
$("#tab_inbox").hide();
}
Or try core JavaScript and use
window.onload = function() {
// code here
}
window.onload waits until everything is loaded on your page, while jQuery's .ready() may fire before images and other media are loaded.
you can try making your own function with pure JS:
document.getElementById('triggerElement').addEventListener('click', funtction(e) {
document.getElementById('hideElement').style.display = 'none';
document.getElementById('showElement').style.display = 'block';
}, false);

Hide/show a icon depending upon the location.search?

Let us say i have a page http://www.abc.com/xyz.html and i am going to access this page in two ways
simple as it is
I will append some stuff to the url e.g. http://www.abc.com/xyz.html?nohome by just putting the value ?nohome manually in the code.
Now i will add some javascript code something like this
$(document).ready(function () {
if (location.search=="?value=nohome") {
// wanna hide a button in this current page
}
else {
// just show the original page.
}
});
Any help will be appreciated.
As you are using jQuery to catch the DOM-ready event, I guess a jQuery solution to your problem would be fine, even though the question isn't tagged jQuery:
You can use .hide() to hide and element:
$(document).ready(function () {
if (location.search=="?value=nohome")
{
$("#idOfElementToHide").hide();
}
// Got rid of the else statement, since you didn't want to do anything on else
});

How do I run a jQuery function when any link (a) on my site is clicked

I have a new site build on corecommerce system which does not have much access to HTML and non to PHP. Only thing I can use is JavaScript. Their system is currently not great on page load speed so I wanted at least customers to know something is happening while they wait 5-8 seconds for a page to load. So I found some pieces of code and put them together to show an overlay loading GIF while page is loading. Currently it will run if you click anywhere on the page but I want it to run only when a link (a href) on the site is clicked (any link).
I know you can do a code that will run while page loading but this isn't good enough as it will execute too late (after few seconds)
Anyway, this is my website www.cosmeticsbynature.com and this is the code I use. Any help will be great.
<div id="loading"><img src="doen'tallowmetopostanimage" border=0></div>
<script type="text/javascript">
var ld=(document.all);
var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
if (ns4)
ld=document.loading;
else if (ns6)
ld=document.getElementById("loading").style;
else if (ie4)
ld=document.all.loading.style;
jQuery(document).click(function()
{
if(ns4){ld.visibility="show";}
else if (ns6||ie4)
var pb = document.getElementById("loading");
pb.innerHTML = '<img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0>';
ld.display="block";
});
</script>
Doing this will be easier if you include jQuery in your pages. Once that is done, you can do:
$('a').click(function() {
// .. your code here ..
return true; // return true so that the browser will navigate to the clicked a's href
}
//to select all links on a page in jQuery
jQuery('a')
//and then to bind an event to all links present when this code runs (`.on()` is the same as `.bind()` here)
jQuery('a').on('click', function () {
//my click code here
});
//and to bind to all links even if you add them after the DOM initially loads (`on()` is the same as `.delegate()` here; with slightly different syntax, the event and selector are switched)
jQuery(document).on('click', 'a', function () {
//my click code here
});
Note: .on() is new in jQuery 1.7.
what you are doing is binding the click handler to the document so where ever the user will click the code will be executed, change this piece of code
jQuery(document).click(function()
to
jQuery("a").click(function()
$("a").click(function(){
//show the busy image
});
How about this - I assume #loading { display:none}
<div id="loading"><img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0></div>
<script type="text/javascript">
document.getElementById('loading').style.display='block'; // show the loading immediately
window.onload=function()
document.getElementById('loading').style.display='none'; // hide the loading when done
}
</script>
http://jsfiddle.net/vol7ron/wp7yU/
A problem that I see in most of the answers given is that people assume click events only come from <a> (anchor) tags. In my practice, I often add click events to span and li tags. The answers given do not take those into consideration.
The solution below sniffs for elements that contain both events, which are created with jQuery.click(function(){}) or <htmlelement onclick="" />.
$(document).ready(function(){
// create jQuery event (for test)
$('#jqueryevent').click(function(){alert('jqueryevent');});
// loop through all body elements
$('body *').each(function(){
// check for HTML created onclick
if(this.onclick && this.onclick.toString() != ''){
console.log($(this).text(), this.onclick.toString());
}
// jQuery set click events
if($(this).data('events')){
for (key in($(this).data('events')))
if (key == 'click')
console.log( $(this).text()
, $(this).data('events')[key][0].handler.toString());
}
});
});
Using the above, you might want to create an array and push elements found into the array (every place you see console.log

simulating a click on a <a>-element in javascript

for a website, i am using the jQuery supzersized gallery script: http://buildinternet.com/project/supersized/slideshow/3.2/demo.html
As you can see in the demo, in the bottom right corner there is an little arrow button that toggles a thumbnail bar. There is no option in the config files to automatically blend this in when opening the site.
So i guess i have to simulate a click on that button (the button is the tray-button, see HTML). I tried something like this:
<script>
$(function() {
$('#tray-button').click();
});
</script>
However, this doesnt seem to work in any browsers i tested.
Any idea?
$('#tray-arrow').click(function() {
// prepare an action here, maybe say goodbye.
//
// if #tray-arrow is button or link <a href=...>
// you can allow or disallow going to the link:
// return true; // accept action
// return false; // disallow
});
$('#tray-arrow').trigger('click'); // this is a simulation of click
Try this
$("#tray-arrow").live("click", function () {
// do something
});
I assume that you want to popup the thumbnail bar #thump-tray on page load.
Here's a way to do it:
locate the file supersized.shutter.js and find this code:
// Thumbnail Tray Toggle
$(vars.tray_button).toggle(function(){
$(vars.thumb_tray).stop().animate({bottom : 0, avoidTransforms : true}, 300 );
if ($(vars.tray_arrow).attr('src')) $(vars.tray_arrow).attr("src", vars.image_path + "button-tray-down.png");
return false;
}, function() {
$(vars.thumb_tray).stop().animate({bottom : -$(vars.thumb_tray).height(), avoidTransforms : true}, 300 );
if ($(vars.tray_arrow).attr('src')) $(vars.tray_arrow).attr("src", vars.image_path + "button-tray-up.png");
return false;
});
After it, add:
$(vars.tray_button).click();
Dont forget in your page (demo.html in the plugin), to change
<script type="text/javascript" src="theme/supersized.shutter.min.js"></script>
to
<script type="text/javascript" src="theme/supersized.shutter.js"></script>
instead of using
$(function(){
//jquery magic magic
});
you culd try this witch will work your jquery magic after the full page is loaded (images etc)
$(window).load(function () {
// jquery magic
});
and to simulate a click you culd use // shuld be the same as $('#tray-arrow').click();
$('#tray-arrow').trigger('click',function(){ })
example:
$(window).load(function () {
$('#tray-arrow').trigger('click',function(){
alert('just been clicked!');
})
});
try
<script>
$(function() {
$('#tray-arrow').click();
});
</script>
Make sure that this code is after your carousel is initialized.
This looks like it's a problem of timing the trigger. The plugin also loads on document load, so maybe when you try to bind the event listener the element is not created yet.
Maybe you need to add the listener in something like the theme._init function
http://buildinternet.com/project/supersized/docs.html#theme-init
or somewhere similar.
A problem might be that your plugin detects whether the click has been initiated by a user (real mouse click), or through code (by using $('#id').click() method). If so, it's natural that you can't get any result from clicking the anchor element through code.
Check the source code of your plugin.

Categories

Resources