JavaScript Issue on Table - javascript

I have a table of results from a database and then I have the following JavaScript that allows a user to click a table row, which will then take them to the correct record.
var pathName = window.location.pathname;
$('table tr').click(function(event) {
var modelId = $('section').attr('data-id');
var dataType = $(this).attr('data-type');
var id = $(this).attr('data-id');
if(pathName === '/accounts/' + modelId) {
if(dataType === 'contact') {
pathName = '/contacts';
} else if(dataType === 'note') {
pathName = '/notes';
} else if(dataType === 'opportunity') {
pathName = '/opportunities';
}
} else if(pathName === '/contacts/' + modelId) {
if(dataType === 'note') {
pathName = '/notes';
} else if(dataType === 'opportunity') {
pathName = '/opportunities';
}
} else if(pathName === '/events/' + modelId) {
pathName = '/delegates';
}
var showUrl = pathName + '/' + id;
if(id === undefined) {
event.preventDefault();
} else {
window.location = showUrl;
}
});
THat works great, except that in each table row, I have a form with a button to delete the record, which when clicked bring up a popup. Unfortunately, because now the table rows are clickable to take the user to the correct records, if they click the delete button it attempts to show the popup but then quickly redirects to the record show view.
I'm thinking this could possibly be fixed with CSS but I've tried position: relative; and z-indexing to no avail.
Can anyone point me in the right direction?

In the click event for the form button write this piece of code.
e.stopPropagation();
It will stop the event from bubbling to the parent.

Cancel the click event of the button in order to not propagate it to the table row.

You have to stop propagation on the click of the button:
element.click(function (e) { // 'element' would be your button/a/input
e.stopPropagation();
I've created a little fiddle to demonstrate how this works: http://jsfiddle.net/PVvfV/.

Related

Jquery If Else Statement Issue

I have multiple buttons and when I click each one I want an element associated with that button to slide down and then when I click the same button the same element slides back up. The code below works but if I click one button it slides down then I click the second button nothing happens because it runs the else if part of the code. How would I fix this?
var moreOption = 1;
$(".more-button").click(function(){
var buttonNumber = $(this).attr('buttonNumber');
if (moreOption === 1) {
$("#more"+buttonNumber).slideDown();
moreOption = 2;
} else if (moreOption === 2) {
$("#more"+buttonNumber).slideUp();
moreOption = 1;
}
});
Just use a data-attribute on the button and switch the state manually like this:
<button class="more-button" data-showMore="1" data-buttonNumber="1"/>
$(".more-button").click(function(){
var buttonNumber = $(this).data('buttonNumber');
var moreOption = $(this).data('showMore');
if (moreOption == '1') {
$("#more"+buttonNumber).slideDown();
$(this).data('showMore', '2');
} else if (moreOption == '2') {
$("#more"+buttonNumber).slideUp();
$(this).data('showMore', '1');
}
});

Rewrite URL on location change

I'm looking for a way to rewrite URL of the location when the user want's to change page. So, let's say you have something like this:
<body>
<a href="http://example.com" />
</body>
Is there a way I can catch URL changing moment, and actually modify that URL before location is changed, for example I would like to change href into relative link like \http://example.com and redirect page actually there.
If you just want to trap the link and then modify it then yes, that's quite simple...
$("a").on("click", function(e) {
e.preventDefault(); // stops the link doing its default thing
window.location.href = "something/" + $(this).attr("href");
});
You obviously need to modify the line that changes the location, so that it modifies the href value however you need. I'd also recommend giving the links a class and selecting them with that, as the above code will affect every link on the page.
Finally, this will need to run after the DOM is loaded, so either wrap it in a document.ready handler of your choice, or put it in a script at the bottom of the body.
Demo
You can work from here. Also you will need urlrewrite in htaccess for this to work properly.
$(function () {
$('.buttonn').on('click', function (e) {
var seperator = (window.location.href.indexOf("?") === -1) ? "?" : "&";
if (window.location.href.indexOf("s1") === -1 && window.location.href.indexOf("s2") != -1) {
window.location.href = window.location.href.replace(/&?s2=([^&]$|[^&]*)/i, "&s1=s1");
} else if (window.location.href.indexOf("s1") != -1) {
window.location.href = window.location.href.replace(/&?s1=([^&]$|[^&]*)/i, "&s1=s1");
} else {
window.location.href = window.location.href + seperator + "s1=s1";
}
});
});
$(function () {
$('.buttono').on('click', function (e) {
var seperator = (window.location.href.indexOf("?") === -1) ? "?" : "&";
if (window.location.href.indexOf("s2") === -1 && window.location.href.indexOf("s1") != -1) {
window.location.href = window.location.href.replace(/&?s1=([^&]$|[^&]*)/i, "&s2=s2");
} else if (window.location.href.indexOf("s2") != -1) {
window.location.href = window.location.href.replace(/&?s2=([^&]$|[^&]*)/i, "&s2=s2");
} else {
window.location.href = window.location.href + seperator + "s2=s2";
}
});
});

How to extract the hyper links from a webpage in javascript

As soon as the web page loading is completes and whenever the cursor will be clicked/hover on any hyper links in that web page, I want to extract that particular link on which my mouse clicked/hover. So what is the JavaScript code snippet for this ?
window.onload = function() {
document.onclick = function(e) {
var target = e.srcElement;
if (target != null) {
var href = target.href;
if (href != null) {
alert("link extracted: " + href);
}
}
return false;
};
}
$(document).click(function(e){
if($(e.target).closest('a').length){
alert('You clicked a link');
alert($(e.target).closest('a').attr('href'));
}
else{
alert('You did not click a link');
}
});

Adding keyboard shortcuts (up, down, enter) to search input suggestions div

I have a search suggestion div that appears when you keyUp an input. This works fine, but now I am trying to make keyboard shortcuts in action.
I want a behavior like when you click down keyboard arrow button a span gets selected and if it is selected then another span that is after gets selected, similarly, if you click up arrow an upward span gets selected, when you click enter then link opens.
I am stuck because I could not remove a:hover and could not add classes to it. Even after I have basically no idea how to do it. But I really tried hard and a lot..
Here is a jsfiddle link (type anything in field). maybe somebody will help me.
This code should go when the request is made and data is being returned:
<script type="text/javascript">
$(document).ready(function(){
total = 3;
$(".result-item").mouseenter(
function(){
hovered = $(this).attr("id");
total = 3;
$(".result-item").each(function(){
$(this).children("a").css({
'background-color':'#e4e4e4',
'color':'#000000'
});
$(this).find(".searchheading").css({
'color':'#191919'
});
$(this).find(".searchcaption").css({
'color':'#555555'
});
});
$(this).children("a").css({
'background-color':'#b7b7b7',
'color':'#ffffff'
});
$(this).find(".searchheading").css({
'color':'#ffffff'
});
$(this).find(".searchcaption").css({
'color':'#f1f1f1'
});
}
);
});
</script>
And this code on a page where request is made:
$("#suggestions").hide();
$("#search").bind('keyup', function(event){
if (event.which == 40 || event.which == 38 || event.which == 13) return false;
else
{
hovered = undefined;
lookup($(this).val());
}
});
$("#search").bind('keydown', 'down', function(evt){
if ($("#suggestions").is(":visible"))
{
if (typeof hovered == 'undefined')
{
$("#result-item-0").trigger("mouseenter");
return;
}
count = parseInt($("#"+hovered).attr("count"));
next = (count + 1);
if (next == total)
next = 0;
$("#result-item-"+next).trigger("mouseenter");
}
});
$("#search").bind('keydown', 'up', function(evt){
if ($("#suggestions").is(":visible"))
{
if (typeof hovered == 'undefined')
{
$("#result-item-"+(total-1)).trigger("mouseenter");
return;
}
count = parseInt($("#"+hovered).attr("count"));
prev = (count - 1);
if (prev == -1)
prev = (total-1);
$("#result-item-"+prev).trigger("mouseenter");
}
});
$("#search").bind('keydown', 'return', function(evt){
if ($("#suggestions").is(":visible"))
{
if (typeof hovered == 'undefined')
{
str = $("#search").val();
window.location.href = urlencode(str); // urlencode is a custom function
return false;
}
count = parseInt($("#"+hovered).attr("count"));
current = count;
$("#result-item-"+current).trigger("mouseenter");
$("#suggestions").fadeOut();
window.location.href = $("#"+hovered).children("a").attr("href");
}
});
})
;
Also I removed onkeyup="" attribute on element, this approach is nicer.

How to send Gmail talk messages using Gmails built it method

I want to create a Google Chrome extension that, among other things, will modify the chat text based on what is inputed. I will add a button next to the video, call, and add people buttons below the name, and when clicked will activate the modifications. I don't want to have to put any more scripts on the page than I have to, so I would like to be able to send the messages the way Gmail would be pressing "return" in the chat box. Also I want to to be able to show that both of the people chatting are using my extension by displaying text in the chat box just like the "This chat is off the record" text is, and possibly if both are using it add extra stuff to the chat. What I tried to do was make an imitation textarea and when the user 'sends' it, grab it and modify it, then insert it into the real one and send the new text. I can change the text but can't seem to send it...
Heres what I have so far, I enclosed everything in a setInterval to check if chat box exists and add appropriate stuff to it:
var chatBtnClone = setInterval(function() {
if ($("body").find(".nH .NG").length > 0) { //if chat is active
var clone = $("body").find(".nH .NG .NJ").first();
if (clone.children()[0].className.indexOf("chat") < 0) { //if already added my class
var clonned = clone.clone();
var clonnedChd = clonned.children().first();
clonnedChd.attr("title", "Start encrypted chat");
clonnedChd.on('click', function() {
console.log("clicked chatBtn!"); //make sure it works
var self = $(this);
if (self[0].className.indexOf("chatEncX") >= 0) { //toggle button pic
self.removeClass('chatEncX').addClass('chatEnc');
self.attr("title", "Stop encrypted chat");
} else {
self.removeClass('chatEnc').addClass('chatEncX');
self.attr("title", "Start encrypted chat");
}
});
clone.parent().prepend(clonned);
clonned.find('.NK').removeClass("NK-Y8").addClass("chatEncX");
}
var chatBoxs = $('body').find(".nn .AD");
var chatArea = chatBoxs.first().find(".nH textarea"); //get chat textareas
if (chatArea.length === 1) {
var clonChatArea = chatArea.first().clone();
clonChatArea.removeAttr("id");
chatArea.first().parent().append(clonChatArea);
// chatArea.first().hide();
var chatTextDiv = chatBoxs.first().find(".jp .nH .nH").first();
clonChatArea.focusin(function() {
chatTextDiv.removeClass("gv").addClass("f7");
});
clonChatArea.focusout(function() {
chatTextDiv.removeClass("f7").addClass("gv");
});
clonChatArea.on('keyup', function(event) {
var self = this;
//console.log(this.style.height); //make sure height it working
if (self.scrollHeight === 38) {
self.style.overflowY = "hidden";
self.style.height = "36px";
} else if (self.scrollHeight === 47) {
self.style.height = "54px";
} else if (self.scrollHeight === 62) {
self.style.height = "72px";
} else if (self.scrollHeight >= 77) {
self.style.height = "80px";
self.style.overflowY = "scroll";
}
if( event.keyCode === 13 && event.shiftKey ){
//regular, just insert a newline
} else if (event.keyCode === 13) {
//grab text and modify then reinsert into real textarea
var chatTxt = $(this).val();
var chatHidden = chatBoxs.first().find(".nH textarea").first();
var chatEncTxt = Crypto.AES.encrypt(chatTxt, "pass"); //modify text
//console.log(chatEncTxt);
chatHidden.val(chatEncTxt);
chatHidden.focus();
chatHidden.trigger({ type : 'keypress', which : 13 }); //try to imitate the return key and send (NOT WORKING!!!)
// $(this).focus();
}
});
}
}
},150);
This might be a bit late, but if anyone else is interested then I managed this by doing the following:
var e = new Event("keypress");
e.keyCode = e.which = 13;
// :mc is an example textarea id, but the OP has the code for finding that already
document.getElementById(':mc').dispatchEvent(e);

Categories