Karolina Ticha Karolina Ticha - 1 year ago 63
Javascript Question

Append element on multiple if conditions

I have this table:

<td>Paul Johnson</td>
<td>28th May 1974</td>
<td>Fake Street 148</td>
<td>New York</td>

There is a script that is executed by mouseenter event

$('th').on("mouseenter mouseleave", function(e) {if (e.type === 'mouseenter') {


inside it is code below

var toolbar = $("<div />").css({
"padding": "5px",
"background" : "#F8F8F8"
"borderRadius" : "5px 0 5px 5px",
"left" : "-30px",
"top" : "0",
"zIndex" : "99"

toolbar.append( gmaps ).append( google ).append( phone ).append( copy );

$(this).append( toolbar );

and link inside toolbar

var link = $("<a />").css({
"display" : "block",
"height" : "20px",
"width" : "20px",
"marginBottom" : "5px",
"background-size" : "100%",
"position" : "relative"})
.attr({"target" : "_blank"

There are many kinds of links, more than 100 variants. There is for example two of them

var thisNext = $( $(this).parent().next('td') ).text();

var gmaps = link.clone().css({
"background" : "url(https://dl.dropboxusercontent.com/s/pwcubxu7xoigavz/maps.png) no-repeat",
"background-size": "100%",
}).attr({href: 'https://www.google.com/maps/search/' + thisNext });

var google = link.clone().css({
"background" : "url(https://dl.dropboxusercontent.com/s/ja0plpnomx3v0jn/find.png) no-repeat",
"background-size": "100%",
}).attr({href: 'https://www.google.cz/search?q=' + thisNext });

I have got more tables on site, but table like this shouldnt append nothing


My questions/goals:

  • variable thisNext should get data from next td element ( if user
    clicks to name, it should get Paul Johnson etc ), but my code do not

  • not each th should append toolbar, for exemple City should do nothing - vhat is the best solution to define which elements should append toolbar?

  • if is user "John" th element street should append gmaps and
    google inside toolbar, if is user "Steve" same element should append only google. For another th element should "Steve" get both links, "John" nothing etc.

here is codepen

I cant make it with classes, ids etc. I need to make only with raw table just like I posted.

Answer Source

Alternate solution using hashmap of options based on known names as keys and indexing of dom elements:

var config = {
  "John" : {"map": "gmap", "links":[1,4,6]},
  "Steve" : {"map": "bing", "links":'all'}

Assume table is first table in page and toolbar goes in 2nd cell on row where name is also located

var $table = $('table').eq(0);
$table.find('tr>th:eq(1)').on("mouseenter mouseleave", function(e) {
        var opts = config[$(this).text()];
        if (e.type === 'mouseenter') {

This will certainly take some fine tuning but using indexing is likely your best approach

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download